<?php

/**
 *
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * @return unknown_type
 */
function form_city($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'update':{
			if ($inf['vhead']['city'] && $post[$key] == $inf['vhead']['city']) {
				$post[$key] = 'NULL';
			}
			if ($inf['vhead']['postcode'] && $post[$inf['prefix'].'postcode'] == $inf['vhead']['postcode']) {
				$post[$inf['prefix'].'postcode'] = 'NULL';
			}
			
			$qry = '`'.$key.'`='.intoDB($post[$key],'S').', `'.$inf['prefix'].'postcode`='.intoDB($post[$inf['prefix'].'postcode'], 'S');
			return array('qry' => $qry);
		} break;
		case 'validate':{
			return;
		} break;
		default: {			
			if ($inf['displayonly']) {
				return trim(clean($inf['default']['city'].$default_state.' '.$inf['default']['postcode']));
			}
			$r = form_input($key, array('default' => $inf['default']['city'], 'param1' => $inf['param1']['city'], 'param2' => $inf['param2']['city'], 'vhead' => $inf['vhead']['city'], 'addon_field' => $inf['addon_field'])).' ';
			$r .= $field_state;
			$r .= form_input($inf['prefix'].'postcode', array('param1' => $inf['param1']['postcode'], 'param2' => $inf['param2']['postcode'], 'default' => $inf['default']['postcode'], 'vhead' => $inf['vhead']['postcode'], 'addon_field' => $inf['addon_field']));

			return $r.$inf['append'];
		}
	}
}

/**
 * new function show daterange by jquery
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * @return unknown_type
 * @since 09 04 2009
 */
function form_daterange($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'update':{
			if (strstr($post[$key],'to')) {
				$post[$key] = explode('to', $post[$key]);
			}
			if (is_array($post[$key])) {
				$qry = '`'.$key.'_from`="'.date('Y-m-d', strtotime($post[$key][0])).'", `'.$key.'_to`="'.date('Y-m-d', strtotime($post[$key][1])).'"';
			} else {
				$qry = '`'.$key.'_from`="'.date('Y-m-d', strtotime($post[$key])).'", `'.$key.'_to`="'.date('Y-m-d', strtotime($post[$key])).'"';
			}
			return array('qry' => $qry);
			break;
		}
		case 'validate':{
			return;
		} break;
		default: {
			if ($inf['default'] == '') {
				$inf['default'] = $inf['head'];
				$js_default = '';
			} else {
				if ($inf['default'] != $inf['head']) {
					if (!is_array($inf['default'])) {
						if (strstr($inf['default'],'to')) {
							$inf['default'] = explode('to', $inf['default']);
						}
					}
					if (is_array($inf['default'])) {
						$js_default = 'dateStart: "'.date(CALENDAR_FORMAT, strtotime($inf['default'][0])).'", dateEnd: "'.date(CALENDAR_FORMAT,strtotime($inf['default'][1])).'"';
						$inf['default'] = date(CALENDAR_FORMAT, strtotime($inf['default'][0])).' to '.date(CALENDAR_FORMAT, strtotime($inf['default'][1]));
					} else {
						$js_default = 'dateStart: "'.date(CALENDAR_FORMAT, strtotime($inf['default'])).'"';
						if ($inf['default']) {
							$inf['default'] = date(CALENDAR_FORMAT, strtotime($inf['default']));
						}
					}
				}
			}
			if ($inf['displayonly'] == 1) {
				if ($inf['default'] != '') {
					return $inf['default'].$inf['append'];
				} else {
					return;
				}
			}
			$id_key = str_replace('[', '_', $key);
			$id_key = str_replace(']', '_', $id_key);

			if ($inf['addon_field']) {
				if (trim($inf['addon_field']['onchange']) != '') {
					$js_default .= '
					onChange: function(){
						'.$inf['addon_field']['onchange'].';
					},';
				}
			}
			if ($inf['default_search'] != '') {
				$default_search = ' default_search="'.$inf['default_search'].'"';
			}
			return '<input id="'.$id_key.'_daterange" name="'.$key.'" def="'.$inf['head'].'" value="'.$inf['default'].'"'.$default_search.' />
			<script type="text/javascript">
				$("input#'.$id_key.'_daterange").daterangepicker({
					arrows:true,
					rangeSplitter: "to",
					dateFormat: "'.CALENDAR_JS_FORMAT.'",
					onOpen: function(){
						var pos = $("input#'.$id_key.'_daterange").offset();
						$("div.ui-daterangepickercontain").attr("style", "position:absolute; top:"+(pos.top+20)+"px; left:"+(pos.left-15)+"px;");
					},
					'.$js_default.'
				});
			</script>';
		}
	}
}

/**
 * type:LU
 * @EXAMPLE1: form_lookup('beem_lookup', array('param2' => array('attr' => 2,'list' => 'officer_list','id_field' => 'id_individual_officer')))
 * @EXAMPLE2: $fields['client_portfolio'] = array('head' => msg('client_portfolio'),'type' => 'E','zone' => 1);
 * ... need more function [PREFIX.'_id_job']for gen listing and [PREFIX.'_job_list']show default
 * IN GAIN PROJECT
 * ... fw_lookup_fields_js, fw_lookup_fields
 *
 */
function form_lookup($key,$inf,$act='form',$post=''){
	if ($act == 'form') {
		if ($inf['displayonly'] == 1) {
			return $inf['default'][1];
		}
		$input_id = $inf['param2']['attr'].'_'.$inf['param2']['id_field'];
		$r = $inf['search'] . form_input($key, array('default' => $inf['default'][1], 'param1' => $inf['param1'], 'addon_field' => ' id="quickSearch'.$inf['param2']['attr'].'" '.$inf['addon_field'].' autocomplete="off"')).'<input id="'.$input_id.'" type="hidden" name="'.$inf['param2']['id_field'].'" value="'.$inf['default'][0].'">
		<a class="clientIDbutton" href="#dontMove" style="display: none;"> <img alt="remove" title="remove link" src="im/remove.png" onclick="fw_remove_lookup(this, \''.$inf['param2']['attr'].'\')"/></a>';
		$r .= "
		<script type='text/javascript'>
			$(document).ready(function(){
				if ($('#quickSearch".$inf['param2']['attr']."').parent().children('input[type=hidden]').val()>0) {
					$('#quickSearch".$inf['param2']['attr']."').parent().children('.clientIDbutton').css('display','inline');
				} else {
					$('#quickSearch".$inf['param2']['attr']."').parent().children('.clientIDbutton').css('display','none');
				}
				quickSearchOld['".$inf['param2']['attr']."'] = '".cleanupJS($inf['default'][1])."';
				quickSearchNew['".$inf['param2']['attr']."'] = '".cleanupJS($inf['default'][1])."';
				$(\"#quickSearch". $inf['param2']['attr'] ."\").keyup(function(event){
					clearTimeout(quickSearchTimeOut['".$inf['param2']['attr']."']);
					quickSearchTimeOut['".$inf['param2']['attr']."'] = setTimeout(\"fw_quick_search('". $inf['param2']['attr'] ."', '". $inf['default'][0] ."', 'fajax=1&mod=".$inf['param2']['list']."');\",1000);
				});

				fw_quickSearchResult_link('".$inf['param2']['attr']."', 'index.php?fajax=1&mod=".$inf['param2']['list']."');

				$(\"#quickSearch". $inf['param2']['attr'] ."\").parents(\"form\").bind({
					submit: function () {
						fw_quickSearchResult_value('".$inf['param2']['attr']."', false);
					}
				});
			});
		</script>";
		return $r;
	}
}

/**
 *
 * @param $field_name
 * @param $field_id
 * @param $default
 * @param $n
 * @param $view
 * @param $fname
 * @param $param1
 * @param $addon_field
 * @return unknown_type
 */
function fw_lookup_fields($field_name, $field_id, $default, $n, $view, $fname, $param1 = 140, $addon_field = ''){
	return form_lookup($field_name, array('default' => array($field_id, $default), 'param1' => $param1, 'param2' => array('attr' => $n, 'list' => $view, 'id_field' => 'id_'.$field_name), 'addon_field' => $addon_field));
}

/**
 *
 * @param $rsl
 * @param $field
 * @param $mod
 * @param $n
 * @param $js_add
 * @return unknown_type
 */
function fw_lookup_fields_js($rsl, $field, $mod, $n, $js_add = array()){
	global $cm_menu;
	//$add_item = '---'.$mod;
	$searchInfo = $_POST['searchInfo'];
	$max_rsl = 10;
	$num_all_rsl = count($rsl);
	if ($_REQUEST['p']) {
		$p = $_REQUEST['p'];
	} else {
		$p = 0;
	}
	$next_p = ($p+1);
	if ($_REQUEST['p'] != 'all') {
		$start = $p*$max_rsl;
		$end = $start+$max_rsl;
	} else {
		$start = 0;
		$end = $num_all_rsl;
	}
	$more_link = 'Type more characters to narrow your search';

	if ($p && $p != 'all') {
		if ($rsl) {
			$j = 0;
			foreach ($rsl as $id => $name) {
				if ($j > $start && $j <= $end) {
					$r .= '<div><a href="#dontMove" rel="'.$id.'" title="'.clean($name).'"><img class="clickMe" alt="accept" title="choose this '.$mod.'" src="im/accept.png" /> '.clean($name).'</a></div>';
				}
				$j++;
			}
		}
		if ($num_all_rsl > $end) {
			$r .= $more_link;
		}
	} else {
		$r = '<div style="margin-right: 15px; padding-bottom: 0px; margin-bottom: 5px; margin-top: 5px;" id="quickSearchResultIn'.$n.'">';
		if (!$rsl) {
			$r .= 'no results'.$add_item;
		} else {
			if ($searchInfo) {
				$r .= 'Total result: '.$num_all_rsl;
			} else {
				$more_link = '';
			}
			$j = 0;
			foreach ($rsl as $id => $name) {
				if ($j >= $start && $j < $end) {
					$r .= '<div><a href="#dontMove" rel="'.$id.'" title="'.clean($name).'"><img class="clickMe" alt="accept" title="choose this '.$mod.'" src="im/accept.png" /> '.clean($name).'</a></div>';
				}
				$j++;
			}

			if ($num_all_rsl > $end) {
				$r .= $more_link;
			}
			$r .= $add_item;
		}
		$r .= '</div>';
	}
	$r .= "
	<script type=\"text/javascript\">
		$(document).ready(function(){
			$('#quickSearchResultIn".$n." a').bind('click', function(){
				var old_v = fw_quickSearchResult_value('".$n."');
				var new_v = fw_quickSearchResult_value('".$n."', $(this).attr('rel'));
				if ($(this).attr('title') != '') {
					$('#quickSearch".$n."').parent().children('.clientIDbutton').css('display','inline');
					quickSearchOld['".$n."'] = $(this).attr('title');
					quickSearchNew['".$n."'] = $(this).attr('title');
					$('#popup'+popID).parents('.ui-dialog').remove();
					$('#quickSearch".$n."').val($(this).attr('title'));
					$('#".$n."_".$field."').val($(this).attr('rel'));
				}
				if (old_v != new_v) {
					".$js_add['onclick']."
				}
			});
			".$js_add['onload']."
			auto_select_client(".count($rsl).", '".$n."');
		});
	</script>
	";
	return $r;
}

/**
 *
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * @return unknown_type
 */
function form_select_group($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
			break;
		}
		case 'update':{
			$po[$key] = $post[$key];
			$qry = '`'.$key.'`='.intoDB($post[$key], 'S');
			return array('qry' => $qry, 'po' => $po);
			break;
		}
		default:{
			if ($inf['displayonly'] == 1) {
				$all = array();
				//flat second dimension and display value
				if ($inf['values']['label']) {
					foreach ($inf['values']['label'] as $k => $v) {
						if ($v) {
							foreach ($v as $k2 => $v2) {
								$all[$k2] = $v2;
							}
						}
					}
				}
				return clean($all[$inf['default']]);
			}
			$inf['default'] = cleanForm($inf['default']);//cleanup data
			$readonly = '';
			$style = '';
			$field_id = 'field_'.$key;
			$selected = '';
			if (!is_array($inf['values'])) {
				return;
			}
			// change into return VALUE <input type="hidden">
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			}
			if ($inf['param1']) {
				$style = ' style="width: '.$inf['param1'].'px;"';
			}
			$r = '<select'.$style.$readonly.$inf['addon_field'].' name="'.$key.'">';
			if ($inf['search'] == 1) {
				$c = $d = $e = '';
				if ($inf['default'] == 'all') {
					$c = ' selected="selected"';
				} else if ($inf['default'] == 'none') {
					$d = ' selected="selected"';
				} else if ($inf['default'] == '') {
					$e = ' selected="selected"';
				}

				$a = '<option'.$e.'></option>';
				$z = '<option value="all"'.$c.'>'.msg('all').'</option>';
				$z .= '<option value="none"'.$d.'>'.msg('none').'</option>';
			}

			if ($inf['req'] != 1) {
				$r .= '<option value="" selected></option>';
			}
			$r .= $z;
			if ($inf['values'][0]) {
				$r .= '<option value="" selected>'.$inf['values'][0].'</option>';
			}
			if (is_array($inf['values']['label'])) {
				foreach ($inf['values']['label'] as $label => $val) {
					if (!is_array($val)) {
						$r .= '<option value="'.$label.'"';
						if ($label == $inf['default']) {
							$r .= ' selected';
						}
						$r .= '>'.$val.'</option>';
					} else {
						$r .= '<optgroup label="'.$label.'">';
						if ($val) {
							foreach ($val as $ky => $vl) {
								$r .= '<option value="'.$ky.'"';
								if ($ky == $inf['default']) {
									$r .= ' selected';
								}
								$r .= '>'.$vl.'</option>';
							}
						}
						$r .= '</optgroup>';
					}
				}
			}
			$r .= '</select>';
			if($inf['append']){
				$r .= $inf['append'];
			}
			return $r;
		}
	}
}

/**
 * use for create select form with out fw
 *
 * @param string $key - field name
 * @param array $inf - 'values' (array of data)
 * @param array $inf - 'default' (set default value)
 * @param array $inf - readonly
 *
 * @example $company = array('1' => 'NSA','2' => 'NSSF');
 * @example form_select('company',array('values' => $company, 'default' => 2,'param1' => '200:20','readonly' => 0));
 *
 * @return string of select form
 * 'set_id' => 1
 * @return '<span id="key" rel="id_key"></span>'
 */
function form_select($key, $inf, $act = 'form', $post = ''){
	switch($act) {		
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'update':{
			$po[$key] = $post[$key];
			$qry = '`'.$key.'`='.intoDB($post[$key],'S');
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			if ($inf['displayonly'] == 1) {
				if ($inf['cleaned'] == 1) {
					$a = $inf['values'][$inf['default']];
				} else {
					$a = clean($inf['values'][$inf['default']]);
				}

				if ($inf['add_linked'] && $a) {
					$a = '<a href="'.$inf['add_linked'].'">'.$a.'</a>';
				}

				if ($inf['set_id']) {
					$r = '<span id="'.$key.'" rel="'.$inf['default'].'">'.$a.'</span>';
				} else {
					if ($inf['param2'] == 'N') {
						$r = $inf['default'];
					} else {
						$r = $a;
					}
				}
				if ($inf['prepend'] && $inf['default']) {
					$r = $inf['prepend'] . $r;
				}
				if ($inf['append'] && $inf['default']) {
					$r .= $inf['append'];
				}
				$r = str_replace('{{id}}', $inf['default'], $r);
				return $r;
			}

			$inf['default'] = cleanForm($inf['default']);//cleanup data
			$readonly = '';
			$style = '';
			$field_id = 'field_'.$key;

			if (!is_array($inf['values']) && $inf['values'] != '' && $inf['param2'] != 'N') {
				return;
			}
			//read only
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			}
			//disabled
			if ($inf['disabled'] == 1) {
				$readonly = ' disabled';
			}
			//width
			if ($inf['param1']) {
				$style = ' style="width: '.$inf['param1'].'px;"';
			}
			//set vhead
			if ($inf['vhead']) {
				$title = ' title="'.$inf['vhead'].'"';
			}

			//set search default TODO need?
			if ($inf['default_search'] != '') {
				$default_search = ' default_search="'.$inf['default_search'].'"';
			}

			$r = '<select'.$style.$readonly.$inf['addon_field'].$title.$default_search.' name="'.$key.'">';

			$first = '<option>'.$inf['vhead'].'</option>';
			//add all/none/empty for search
			if ($inf['search'] == 1) {
				$c = $d = $e = '';
				if ($inf['default'] == 'all') {
					$c = ' selected="selected"';
				} else if ($inf['default'] == 'none') {
					$d = ' selected="selected"';
				} else if ($inf['default'] == '') {
					$e = ' selected="selected"';
				}

				$options_search = '<option value="all"'.$c.'>' . msg('all') . '</option>';
				$options_search .= '<option value="none"'.$d.'>' . msg('none') . '</option>';
			} else {
				if ($inf['req'] == 1) {
					if ($inf['empty_show'] != 1) {
						//show empty
						$first = '';
					}
				} else {
					if ($inf['empty_hide'] == 1) {
						//hide empty
						$first = '';
					}
				}
			}

			//example: form_select('per_page',array('default' => 20,'param2' => 'N','values' => '1:20:5'));
			if ($inf['param2'] == 'N') {//normal array
				if (($inf['default'] != '' && $inf['default'] != 'none' && $inf['default'] != 'all') && is_array($inf['values']) && !in_array($inf['default'],$inf['values'])) {
					$inf['values'][] = $inf['default'];
				}

				if (is_string($inf['values'])) {
					$n = explode(':', $inf['values']);
					$inf['values'] = array();
					$i = $n[0];
					if ((int)$n[2] == 0) {
						$n[2] = 1;
					}
					for ($i = $n[0]; $i <= $n[1]; $i++) {
						$inf['values'][] = $i*$n[2];
					}
				}

				if (is_array($inf['values'])) {
					$second = '';
					foreach ($inf['values'] as $ky => $vl) {
						$second .= '<option';
						if ($vl == $inf['default']) {
							$second .= ' selected="selected"';
						}
						$second .= '>'.$vl.'</option>';
					}
				}
				$r .= $first . $second . $options_search;
				$r .= '</select>';
			} else {//associated array
				if (($inf['default'] != 'all' && $inf['default'] != 'none' && $inf['default'] != '' && $inf['default'] != '0') && is_array($inf['values']) && !array_key_exists($inf['default'], $inf['values'])) {
					$inf['values'][$inf['default']] = $inf['default'];
				}

				//keep hidden fields for keep value
				if ($inf['values'] && count($inf['values']) == 1 && $inf['force_select'] != 1 && $inf['req'] == 1 && 1==2) {
					$ky = array_keys($inf['values']);
					$vl = array_values($inf['values']);

					if ($inf['msg'] == 1) {
						$vl[0] = msg($vl[0]);
					}
					$r = $vl[0].'<input type="hidden" name="'.$key.'" value="'.$ky[0].'"/>';

				} else {
					if ($inf['values']) {
						$second = '';
						foreach ($inf['values'] as $ky => $vl) {
							$second .= '<option value="'.$ky.'"';
							if ($ky != '' && strcmp( $ky, $inf['default'] ) === 0  && $set_default == 0) {
								$set_default = 1;
								$second .= ' selected="selected"';
							}
							if ($inf['msg'] == 1) {
								$vl = msg($vl);
							}
							$second .= '>'.$vl.'</option>';
						}
					}

					$r .= $first . $second . $options_search;
					$r .= '</select>';
				}
			}

			//prepend
			if ($inf['prepend']) {
				$r = $inf['prepend'].$r;
			}

			//append
			if ($inf['append']) {
				$r .= $inf['append'];
			}
			$r = str_replace('{{id}}', $inf['default'], $r);

			//for sort by js table
			if ($inf['set_id']) {
				return '<span id="'.$key.'" rel="'.$inf['default'].'">'.$r.'</span>';
			} else {
				return $r;
			}
		}
	}
}

/**
 *
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * @return unknown_type
 */
function form_select_group_multi($key, $inf, $act = 'form', $post = '') {
	switch($act) {
		case 'validate': {
			if (!isset($post[$key]) || COUNT($post[$key]) == 0) {
				return $key;
			}
		} break;
		case 'update':{
			return;
		} break;
		default:{
			$r = '';
			if ($inf['displayonly'] == 1) { //show detail
				return $r;
			}

			// show form

			//check default
			$inf['default'] = cleanForm($inf['default']);//cleanup data
			//check readonly
			$readonly = '';
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			}
			if (!is_array($inf['values'])) {
				return;
			}
			//check param1
			if ($inf['param1']) {
				$width = 'minWidth:'.$inf['param1'].',';
			}

			if ($inf['addon_field']) {
				$addon_field = '
					onCheck: function(){
						'.$inf['addon_field'].'
					},
					onCheckAll: function(){
						'.$inf['addon_field'].'
					},
					onUncheckAll: function(){
						'.$inf['addon_field'].'
					},
					onOptgroupToggle: function(){
						'.$inf['addon_field'].'
					},
					';
			}
			//set form select and add js
			$r .= '<select multiple="multiple" id="'.$key.'" name="'.$key.'[]">';
			if (is_array($inf['values']['label'])) {
				foreach ($inf['values']['label'] as $label => $val) {
					$r .= '<optgroup label="'.$label.'">';
					foreach ($val as $ky => $vl) {
						$r .= '<option value="'.$ky.'"';
						if ($ky == $inf['default'] || $inf['param2'] == 'selected_all') {
							$r .= ' selected';
						}
						$r .= '>'.$vl.'</option>';
					}
					$r .= '</optgrout>';
				}
			}
			$r .= '</select>
			<script type="text/javascript">
				$(document).ready(function(){
				    $("select[name=\''.$key.'[]\']").multiSelect({
						'.$width.$addon_field.'
					});
				});
			</script>
			';
			return $r;
		}
	}
}

/**
 * use for create select form with out fw
 *
 * @param string $key - field name
 * @param array $inf - 'values' (array of data)
 * @param array $inf - 'default' (set default value)
 * @param array $inf - 'param1' (set [width:size] for select form
 * @param array $inf - readonly
 *
 * @example $company = array('1' => 'NSA','2' => 'NSSF');
 * @example form_select('company',array('values' => $company, 'default' => 2,'param1' => '200:20','readonly' => 0));
 *
 * @return string of select form
 * @param{new}
 *
 *
 */
function form_select_multi($key,$inf,$act='form',$post=''){
	switch($act) {
		case 'validate':{
			return 1;
		} break;
		case 'update':{
			return ;
		} break;
		default:{
			$r = '';
			if ($inf['displayonly'] == 1) {
				if (isset($inf['default'])) {
					//set loop for show data
					foreach ($inf['default'] as $k => $v) {
						$r .= clean($inf['values'][$k]).'<br/>'."\n";
					}
					return trim($r);
				}
				return;
			}
			$inf['default'] = cleanForm($inf['default']);//cleanup data
			$readonly = '';
			if (!is_array($inf['values'])) return;
			//TODO change into return multiple <input type="hidden">
			if ($inf['readonly'] == 1) $readonly = ' readonly';
			if ($inf['param1']) {
				$param1 = explode(':',$inf['param1']);
				if ($param1[1]) $style .= ' style="width: '.$param1[1].'px;"';
				if ($param1[0]) $size = ' size="'.$param1[0].'"';
			}
			$r = '<select multiple'.$style.$size.$readonly.$inf['addon_field'].' name="'.$key.'[]">';
			if (is_array($inf['default'])) $isArray = 1;
			foreach ($inf['values'] as $ky => $vl) {
				$r .= '<option value="'.$ky.'"';
				if ($isArray == 1) {
					if (in_array($ky,$inf['default'])) {
						$r .= ' selected';
					}
				}
				$r .= '>'.$vl.'</option>';
			}
			$r .= '</select>';
			return $r;
		}
	}
}

/**
 * checkbox form without fw
 *
 * @param string $key - field name
 * @param array $inf - 'values' (array of data)
 * @param array $inf - 'default' (set default value)
 * @param array $inf - 'param1' (set separator between value)
 * @param array $inf - 'readonly'
 *
 * @example $company = array('1' => 'NSA','2' => 'NSSF');
 * @example form_checkbox('company',array('values' => $company, 'default' => 2,'param1' => '<br/>','readonly' => 0));
 *
 * $multi = array('multi' => 'X','qry_col_value' => 'id_role', 'qry_tab' => 'gain_user_role','qry_col_check' => 'id_user');
 * $fields['security_group'] = array('H' => msg('security_group'),'T' => 'C','multi' => $multi, 'param1' => '<br />','values' => $role, 'zone' => 1);
 *
 * @return string of checkbox form
 */
function form_checkbox($key, $inf, $act = 'form', $post = '', $id_prefix = ''){
	global $db;
	if ($inf['bullet'] == 1) {
		$dash = '- ';
	}
	switch($act) {
		case 'validate':{
			if (!isset($post[$key])) return $key;
			return false;
		} break;
		case 'update':{
			if ($inf['multi'] == 'Z') {
				$po[$key] = $post[$key];
				$qry = '`'.$key.'`='.intoDB($post[$key]);
				return array('qry' => $qry, 'po' => $po);
			} else {//multi
				if ($post['merge'] == 1) {
					$sql = $inf['multi']['qry_del'].$post['id_item_update'];
					$db->Execute($sql, 'fw');
					$sql = 'UPDATE '.$inf['multi']['qry_tab'].' SET '.$inf['multi']['qry_col_check'].'='.$post['id_item_update'].' WHERE '.$inf['multi']['qry_col_check'].'='.$post['id'];
					$db->Execute($sql, 'fw');
				}
			}
		} break;
		default:{
			$r = '';
			$isArray = '';
			if (is_array($inf['default'])) {
				$isArray = 1;
			}
			//seperate multi items, kept in one value field
			if ($isArray != 1) {
				if (strstr($inf['default'], ':')) {
					$inf['default'] = split(':', $inf['default']);//TODO what if the value is ":"
					$isArray = 1;
				}
			}
			if (!is_array($inf['values'])) {
				return;
			}
			if ($inf['displayonly'] == 1) {
				if (isset($inf['default'])) {
					if ($inf['cleaned'] != 1) {
						$inf['values'] = clean($inf['values']);
					}
					if ($isArray != 1) {
						return $inf['default'];
					} else {
						//set loop for show data
						$array_total = count($inf['default']);
						foreach ($inf['default'] as $k => $v) {
							if ($inf['link']) {
								$name = '<a href="'.str_replace('{{id}}', $v, $inf['link']).'">'.$inf['values'][$v].'</a>';
							} else {
								$name = $inf['values'][$v];
							}
							
							if (++$c == $array_total) {
								$inf['param1'] = '';
							}
							if ($inf['values'][$v]) {								
								$r .= $dash.$name.$inf['param1']."\n";
							}
						}
					}
					return trim($r);
				} else {
					return '---';
				}
			}

			$inf['default'] = cleanForm($inf['default']);//cleanup data
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			} else {
				$readonly = '';
			}

			if ($inf['disabled'] == 1) {
				$disabled = ' disabled';
			} else {
				$disabled = '';
			}

			if ($inf['align']) {
				$align = $inf['align'];
			} else {
				$align = 'v';
			}

			if ($id_prefix != '') {
			    $id_prefix .= '-check-'.$key;
			} else {
			    $id_prefix = 'check-'.$key;
			}

			foreach ($inf['values'] as $k => $v) {
				$field_id = $id_prefix.'-'.$k;
				$option_hide = '';
				if ($inf['option_hide']) {
					if (in_array($k, $inf['option_hide'])) {
						$option_hide = ' hide';
					}
				}
				if ($inf['single'] == 1) {
					$r .= '<p class="input_align_'.$align.$option_hide.'"><input'.$disabled.$readonly.$inf['addon_field'].' id="'.$field_id.'" class="brd0" type="checkbox" name="'.$key.'" value="'.$k.'"';
				} else {
					$r .= '<p class="input_align_'.$align.$option_hide.'"><input'.$disabled.$readonly.$inf['addon_field'].' id="'.$field_id.'" class="brd0" type="checkbox" name="'.$key.'[]" value="'.$k.'"';
				}

				if ($isArray == 1) {
					if (in_array($k,$inf['default'])) {
						$r .= ' checked';
					}
				} else if ($k == $inf['default']) {
					$r .= 'checked';
				}
				$r .= ' > <label for="'.$field_id.'">'.$v.'</label> ' . $inf['append'] . '</p>';
			}

			if ($inf['search_show'] == 3 && $inf['head'] != '') {
				return '<div style="float: left; margin-right: 8px;">'.$inf['head'].': </div> <div>'.$r.'</div>';
			}
			return $r;
		}
	}
}

/**
 * input form with out fw
 *
 * @param string $key field name
 * @param $inf - 'values[0]'
 * @param $inf - 'param1' set [width] for form)
 * @param $inf - 'param2' (set maxlenght for form)
 * @param $inf - 'readonly'
 * @example $value = array('NSA');
 * @example form_input('company', array('value' => $value,'param1' => 200,'param2' => 50,'readonly' => 0,'autocomplete' => 1));
 *
 * @example for tags
 * set 'tags' => array('table' => 'gain_client'),
 * 'param2' => 'multi'
 *
 * @example autocomplete
 * form_input('beem', array('value' => $value,'param1' => 200,'param2' => 50,'readonly' => 0,'autocomplete' => array('url' => 'index.php','col' => 'login','tab' => 'mt_user')));
 * @return string of input form
 */
function form_input($key, $inf, $act = 'form', $post = ''){
	global $db;
	//check values
	if (function_exists($inf['call_function'])) {
		$inf['default'] = $inf['call_function']($key, $inf);
	}

	$readonly = '';
	if ($inf['values'] != '') {
		$inf['default'] = $inf['values'][0];
	}

	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'search_result':{
			if ($inf['link']) {
				return array(
					'entity_link' => 1,
				);
			} else {
				return array(
					'cut' => 1,
				);
			}
		} break;
		case 'update':{
			if ($inf['param2'] > 0) {
				$post[$key] = substr($post[$key], 0, $inf['param2']);
			}
			if ($inf['vhead'] && $post[$key] == $inf['vhead']) {
				$post[$key] = 'NULL';
			}
			$po[$key] = $post[$key];
			$qry = '`'.$key.'`='.intoDB($post[$key]);
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			if ($inf['displayonly'] == 1) {
				if ($inf['default'] != '') {
					if (isset($inf['call_function'])) {
						$inf['default'] = '<span name="'.$key.'">'.$inf['default'].'</span>';
					}
					return clean($inf['default']) . $inf['append'];
				} else {
					return;
				}
			}

			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			}

			if ($inf['param1']) {
				$style .= ' style="';
				$a = explode('|', $inf['param1']);
				if (isset($a[0])) {
					$style .= 'width: '.$a[0].'px;';
				}
				if (isset($a[1])) {
					if (strstr($a[1], 'C')) {
						$style .= 'text-align: center;';
					}
					if (strstr($a[1], 'B')) {
						$style .= 'font-weight: bold;';
					}
					if (strstr($a[1], 'R')) {
						$style .= 'text-align: right;';
					}
				}
				$style .= '"';
			}

			if ($inf['param2'] > 0) {
				$maxlen = ' maxlength="'.$inf['param2'].'"';
			}

			if ($inf['attr']) {
				$rel = $inf['attr'] . '_';
			}
			$ar = array('[', ']');
			$rel .= str_replace($ar, '', $key);
			if ($inf['vhead']) {
				$title = ' title="'.$inf['vhead'].'"';
			}
			if ($inf['tags'] || $inf['duplicate_check'] == 1) {
				$inf['addon_field'] .= ' id="'.$rel.'"';
			}

			if (isset($inf['prepend'])) {
				$r .= $inf['prepend'];
			}

			$r .= '<input type="text" rel="'.$rel.'" name="'.$key.'"'.$maxlen.$style.$readonly.$inf['addon_field'].' value="'.cleanForm($inf['default']).'"'.$title.'/>' . $hidden_key;
			if (isset($inf['append'])) {
				$r .= $inf['append'];
			}

			if ($inf['tags'] && ($_REQUEST['link'] == 'edit' || $_REQUEST['link'] == 'add')) {
				if ($inf['tags']['table']) {
					$sql = SQL('SELECT GROUP_CONCAT('.$key.')
					FROM '.$inf['tags']['table'].'
					WHERE removed IS NULL');
					$all_tags = $db->GetCol($sql);
					if ($all_tags) {
						$tags_list = '';
						$tags_array = array();
						foreach ($all_tags as $k => $v) {
							$vx = explode(',', $v);
							if ($vx) {
								foreach ($vx as $k2 => $v2) {
									if ($v2 != '') {
										$v2 = trim($v2);
										$tags_array[$v2] = 1;
									}
								}
							}
						}
					}

					//sort project
					if ($tags_array) {
						$tags_key = array_keys($tags_array);
						natcasesort($tags_key);
						if ($tags_key) {
							foreach ($tags_key as $k => $v) {
								if ($v) {
									$tags_list .= '\''.addslashes(clean($v)).'\',';
								}
							}
						}
					}
				} else if ($inf['tags']['list']) {
					$tags_key = $inf['tags']['list'];
					natcasesort($tags_key);
					if ($tags_key) {
						foreach ($tags_key as $k => $v) {
							if ($v) {
								$tags_list .= '\''.addslashes(clean($v)).'\',';
							}
						}
					}
				}
				$r .= '<script type="text/javascript">
					$(document).ready(function(){
						var availableTags_'.$key.' = ['.$tags_list.'];
						';
				if ($inf['param2'] == 'multi') {
					$r .= '
						$( "#'.$rel.'" )
						.bind( "keydown", function( event ) {
							if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) {
								event.preventDefault();
							}
						})
						.autocomplete({
							minLength: 0,
							source: function( request, response ) {
								// delegate back to autocomplete, but extract the last term
									response( $.ui.autocomplete.filter(
										availableTags_'.$key.', extractLast( request.term )
									)
								);
							},
							focus: function() {
								// prevent value inserted on focus
								return false;
							},
							select: function( event, ui ) {
								var terms = split( this.value );
								// remove the current input
								terms.pop();
								// add the selected item
								terms.push( htmlspecialchars_decode(ui.item.value) );
								// add placeholder to get the comma-and-space at the end
								terms.push( "" );
								this.value = terms.join( ", " );
								//save data
								return false;
							},
							change: function( event, ui ){
								//save data
							}
						});
						';
				} else {
					$r .= '
					$( "#'.$rel.'" ).autocomplete({
						source: availableTags_'.$key.',
						select: function( event, ui ) {
								var terms = split( this.value );
								// remove the current input
								terms.pop();
								// add the selected item
								terms.push( htmlspecialchars_decode(ui.item.value) );
								// add placeholder to get the comma-and-space at the end
								terms.push( "" );
								this.value = terms.join( "" );
								//save data
								return false;
							},
					});';
				}
				$r .= '
					});
				</script>';
			} else if(is_array($inf['value'])){
				$auto = $inf['value'];
				$r .= '
				<script type="text/javascript">
					$(document).ready(function(){
						$( "#'.$rel.'_autocomplete" ).autocomplete({
							source: "index.php?fajax=1&mod='.$inf['value']['autocomplete']['list'].'",
							minLength: 3,
							select: function( event, ui ) {
								$( "#'.$rel.'_id" ) . val(ui.item.id);
							}
						});
					});
				</script>';
			} else if ($inf['duplicate_check'] == 1) {
				$r .= '<div id="notify_duplicated_'.$rel.'"></div>
				<script type="text/javascript">
					$(document).ready(function(){
						$( "#'.$rel.'" ).change(function(){
							if ($(this).val() != "") {
								$.post("index.php?fajax=1&mod=entities&view=duplicate_checked",
								{
									entity: "'.$inf['entity'].'",
									entity_name: $(this).val(),
									entity_id: $("input[name=id]").val(),
									entity_field: "'.$key.'",
								},
									function(data){
										$("#notify_duplicated_'.$rel.'").html(data);
								});
							}
						});
					});
				</script>';
			}
			return $r;
		}
	}
}

/*
 * $fields['id_client'] = array('head' => msg('company'), 'type' => 'autocomplete', 'zone' => $client_zone, 'show' => $hide_header,
		'default' => array('id' => $_REQUEST['add_client_id']), //for add by client page 
		'param1' => '150', 'param2' => '200', 
		'attr' => 2, //defind uniqe field
		'entity' => 'clients',
		'onselect' => '',
		'prepend' => '', //prepend option 
		'call_function' => 'gain_client_details',//for display on detail page
		'entity_table' => $basics['table'],
		'entity_id' => $basics['key'],
	);
 */
function form_autocomplete($key, $inf, $act = 'form', $post = ''){
	global $db;
	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'search_result':{
			return array(
				//'entity_link' => 1,
			);
		} break;
		case 'update':{
			//TODO check for leads
			if (($inf['vhead'] && $post[$key] == $inf['vhead']) || $post[$key] == '') {
				$post[$key] = 'NULL';
			}
			
			$po[$key] = $post[$key];
			$qry = '`'.$key.'`='.intoDB($post[$key]);
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			if ($inf['displayonly'] == 1) {
				if ($inf['call_function']) {
					if (function_exists($inf['call_function'])) {
						return $inf['call_function']($key, $inf);
					} else {
						return $inf['call_function'] . '...'; 
					}
				} else {
					if ($inf['default']['name']) {
						return $inf['prepend'] . clean($inf['default']['name']) . $inf['append'];
					}
				}
				return '';
			}
			unset($inf['call_function']);

			if ($inf['vhead']) {
				$title = ' title="'.$inf['vhead'].'"';
			}
			$id = $inf['default']['id'];
			if (!$inf['default']['name'] && $id) {
				require_once 'modules/'.$inf['entity'].'.php';
				if ($inf['list']) {
					$_REQUEST['type'] = $inf['list'];
				}
				$fn = PREFIX . $inf['entity'] . '_list';
				if (function_exists($fn)) {
					unset($_REQUEST['type']);
					$l = $fn($id);
					$name = $l[$id];
				}
			} else {
				$name = $inf['default']['name'];
			}
			unset($inf['default']);
			$inf['default'] = $name;
			$inf['param1'] = $inf['param1'] - 20;
			if ($inf['search'] == 1) {
				$ar = array('[', ']');
				$field_name = str_replace($ar, '', $key);
				unset($inf['onselect']);
			} else {
				$field_name = $key.'_autocomplete';
				
			}
			$field_id = $key;
			if (!$id) {
				$remove_icon_hide = ' hide';
			}
			$r = $inf['prepend'] . form_input($field_name, $inf) . ' <img class="fw-point' . $remove_icon_hide . '" src="im/remove.png" onclick="$(this).hide().parent().find(\'input\').val(\'\'); '.$inf['onselect'].'" title="'.msg('remove').'"/>';
			$inf['default'] = $id;
			$r .= '<span class="hide">' . form_input($field_id, $inf) . '</span>';
			
			if (isset($inf['append'])) {
				$r .= $inf['append'];
			}
			
			if ($inf['list']) {
				$add_list = '&type=' . $inf['list'];
			}

			$r .= '
				<script type="text/javascript">
					$(document).ready(function(){
						$( "input[name=\''.$field_name.'\']" ).autocomplete({
							source: "index.php?fajax=1&mod='.$inf['entity'].'&view=list'.$add_list.'",
							minLength: 3,
							selectFirst: true,
							autoFocus: true,
							open: function(event, ui) {
							},
							search: function(event, ui) {
							},
							select: function( event, ui ) {
								if ("'.$inf['save_name'].'" == 1) {
									$( "input[name=\''.$field_id.'\']" ) . val(ui.item.value);
									$( "input[name=\''.$field_name.'\']" ).next("img").show();
								} else {
									$( "input[name=\''.$field_id.'\']" ) . val(ui.item.id);
									$( "input[name=\''.$field_name.'\']" ).next("img").show();
								}
								'.$inf['onselect'].'
							},
							change: function(event, ui) {
								if (!ui.item) {
									if ("'.$inf['save_name'].'" == 1) {
										$( "input[name=\''.$field_id.'\']" ) . val($( "input[name=\''.$field_name.'\']" ).val());
									} else {
										$( "input[name=\''.$field_name.'\']" ) . val("") . next("img") . click();
										$( "input[name=\''.$field_id.'\']" ) . val(0);
									}
								}
							},
							focus: function(event, ui) {
							}
						});
					});
				</script>';
			return $r;
		}
	}
}

/**
 * @param $inf - 'param1' set [width] should less than other fields for 80 px
 * @example same input form
 * @return string of input form
 */
function form_email($key, $inf, $act = 'form', $post = ''){
	global $global_config;
	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'update':{
			$po[$key] = $post[$key];
			$qry = '`'.$key.'`='.intoDB(trim($post[$key]), 'S');
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			$inf['addon_field'] .= ' onKeyUp="fw_email_validation(this, \''.msg('valid').'\', \''.msg('invalid').'\');"';
			$r = form_input($key, $inf);
			$r .= '<span></span>';
			if (!empty($inf['default'])) {
				if ($inf['displayonly'] == 1) {
					if (function_exists('gain_plug_email')) {
						$mail_p['item_type'] = $inf['item_type'];
						$mail_p['item_id'] = $inf['item_id'];
						if ($inf['item2_type'] && $inf['item2_id']) {
							$mail_p['item2_type'] = $inf['item2_type'];
							$mail_p['item2_id'] = $inf['item2_id'];
						}
						$mail_p['email'] = $inf['default'];
						if ($inf['name']) {
							$mail_p['name'] = $inf['name'];
						} else {
							$mail_p['name'] = $inf['default'];
						}
						if ($inf['ccb_contact']) {
							$mail_p['id'] = '';
						}
						return gain_plug_email($mail_p);
					} else {
						return '<a target="_blank" href="mailto:'.$inf['default'].'">'.$inf['default'].'</a>';
					}
				}
				//add js validate email!!!
				$r .= '
				<script type="text/javascript">
					fw_email_validation($(\'input[name='.$key.']\'), "'.msg('valid').'", "'.msg('invalid').'");
				</script>';
			} else if ($inf['displayonly'] == 1) {
				return '';
			}
			return $r;
		}
	}
}

/**
 * @example same input form
 * @return string of input form
 */
function form_website($key, $inf, $act = 'form', $post = ''){
	$src_img = '';
	$src_pattern = ' <a alt="'.msg('preview_website').'" title="'.msg('preview_website').'" target="_blank" href="'.clean($inf['default']).'"><img src="im/website.png" style="vertical-align: middle;" /></a>';
	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
		} break;
		case 'update':{
			$po[$key] = $post[$key];
			if ($post[$key] == 'http://' || $post[$key] == $inf['vhead']) {
				$post[$key] = 'NULL';
			}
			$qry .= '`'.$key.'`='.intoDB($post[$key]);
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			if (!empty($inf['default'])) {
				if (!strstr($inf['default'], 'http:') && !strstr($inf['default'], 'https:')) {
					$inf['default'] = 'http://'.clean($inf['default']);
				}
				$src_img = $src_pattern;
			}
			if ($inf['displayonly'] == 1) {
				if ($inf['default']) {
					$r = '<a target="_blank" href="'.clean($inf['default']).'">'.clean($inf['default']).'</a>';
				}
				return $r;
			}
			$r = form_input($key, $inf).$src_img;
			$r .= '
				<script type="text/javascript">
					$(document).ready( function() {
						$(\'input[name='.$key.']\').blur(function () {
							var src_val = $(this).val();
							var $website_ico = $(this).next("a");
							var url_pattern = \''.$src_pattern.'\';
							if($website_ico.length > 0) {
								$website_ico.attr("href", src_val);
							} else {
								$(this).after(url_pattern);
								$(\'input[name='.$key.']\').next("a").attr("href", src_val);
							}						
						});
					});					
				</script>';
			return $r;
		}
	}
}

/**
 * create multi input text field
 *
 * @param string $key
 * @param $inf - param1 width of box
 * @param $inf - param2 maxlength
 * @param $inf - readonly
 * @example form_input_multi('first_name',array('param1' => 200,'param2' => 50,'readonly' => 0);
 *
 * @return input fields
 */
function form_input_multi($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
			return '';
		} break;
		case 'update':{
			return;
		} break;
		default:{
			if ($inf['displayonly'] == 1) {
				if (isset($inf['default'])) {
					foreach ($inf['default'] as $k => $v) {
						$r .= clean($v).'<br/>'."\n";
					}
					return trim($r);
				} else {
					return;
				}
			}
			$inf['default'] = cleanForm($inf['default']);//cleanup data

			$style = '';
			$readonly = '';
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			}
			if ($inf['values'] != '') {
				$inf['default'] = $inf['values'][0];
			}
			//name for fields
			$field_id = 'field_'.$key;
			if ($inf['param1']) {
				$style = ' style="width: '.$inf['param1'].'px;"';
			}
			if ($inf['param2'] > 0) {
				$maxlen = ' maxlength="'.$inf['param2'].'"';
			} else {
				$maxlen = '';
			}
			if (!is_array($inf['default'])) {
				$inf['default'] = explode(':', $inf['default']);
			}
			//set pattern for duplicate input fields
			$r = '<div id="'.$field_id.'_0" style="display: none;">
				<input id="{id}" type="text" name="'.$key.'[]"'.$maxlen.$style.$readonly.$inf['addon_field'].'/>
			</div>';

			if (is_array($inf['default']) && count($inf['default']) > 1) {
				foreach ($inf['default'] as $k => $v) {
					++$j;
					if ($j == 1) {
						$del_botton = '';
					} else {
						$del_botton = ' <img src="im/remove.png" class="fw-point" onclick="replicate_remove_item(\''.$field_id.'_Old'.$k.'\',\''.$field_id.'\')" alt="'.INF_REMOVE.'" title="'.INF_REMOVE.'"/>';
					}
					if ($v != '') {
						$r .= '<div id="'.$field_id.'_Old'.$k.'">'.'<input id="'.$field_id.'_Old'.$k.'" type="text" name="'.$key.'_Old['.$k.']"'.$maxlen.$style.$readonly.$inf['addon_field'].' value="'.$v.'" />'.$del_botton.'</div>';
					}
				}
			} else {
				$r .= '
				<script type="text/javascript">
					replicate_add_item("'.$field_id.'","");
				</script>';
			}
			return $r;
		}
	}
}

/**
 *
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * @return unknown_type
 */
function form_pattern_multi($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
			return '';
		} break;
		case 'update':{
			echo 'beem';
			exit;
			return;
		} break;
		default:{
			//set header table
			if ($inf['pattern']) {
				$tab_h = '<tr class="ui-state-default-black">';
				foreach ($inf['pattern'] as $k => $v) {
					//set table header
					$c = 'fw-form_head';
					if ($v['req'] == 1) {
						$c = 'fw-form_head_r';
					}

					if ($inf['displayonly'] == 1) {
						if ($v['type'] == 'money') {
							$w = ' width="'.$v['param1']['M'].'"';
						} else {
							$w = ' width="'.$v['param1'].'"';
						}
					}

					$tab_h .= '<th class="'.$c.'"'.$w.'>'.$v['head'].'</th>';

					$p_fn = 'form_'.$v['type'];

					if (function_exists($p_fn)){
						$f = $p_fn($k.'[]', $v).' ';
					} else {
						$f = $p_fn.'...';
					}

					$p .= $f;
					$tab_p .= '<td>'.$f.'</td>';
				}
			}
			//for return details
			if ($inf['displayonly'] == 1) {
				if (count($inf['default']) > 0) {
					$row_c = 0;
					$r = '';
					//fw-items_list ui-corner-all ui-widget
					$tab = '<table cellspacing="0" cellpadding="4" class="multi_tbl">'.$tab_h.'</tr>';
					$check_value = 0;
					if ($inf['default']) {
						foreach ($inf['default'] as $k => $v) {
							$tab .= '<tr class="fw-event'.($row_c%2).'">';
							$ck = 0;
							foreach ($inf['pattern'] as $k2 => $v2) {
								$p_fn = 'form_'.$v2['type'];
								if (function_exists($p_fn)) {
									$v2['displayonly'] = 1;
									//TODO check each type
									if ($v2['type'] == 'money') {
										$v2['default'] = array('money' => $v[$k2], 'currency' => $v[$k2.'_currency']);
									} else {
										$v2['default'] = $v[$k2];
									}
									if (trim($v[$k2]) == '') {
										++$ck;
									}
									$f = $p_fn($k.'[]', $v2).' ';
								} else {
									$f = $p_fn.'...';
								}

								$p .= $f;
								$tab .= '<td>'.$f.'</td>';

								$r .= $v[$k2].' ';
							}
							if (count($inf['pattern']) == $ck) {
								++$check_value;
							}
							$r .= '<br/>';
							$tab .= '</tr>';
							$row_c++;
						}
					}
					$tab .= '</table>';
					if ($check_value == count($inf['default'])) {
						$tab = '';
					}
					return $tab;
				} else {
					return;
				}
			}
			//name for fields
			$field_id = 'field_'.$key;
			//set pattern
			$row_c = 0;
			$r = '<div id="'.$field_id.'_0" style="display: none;">'.$p.'</div>';
			//set default
			//fw-items_list ui-corner-all ui-widget
			$tab = '<table cellspacing="0" cellpadding="4" class="input_position">'.$tab_h.'<th></th></tr>
				<tr id="'.$field_id.'_0" style="display: none;">'.$tab_p.'</tr>';
			if (is_array($inf['default']) && count($inf['default']) > 0) {
				foreach ($inf['default'] as $k => $v) {
					++$j;
					$del_botton = ' <img src="im/remove.png" class="fw-point remove_'.$field_id.'" onclick="replicate_remove_item(\''.$field_id.'_Old'.$k.'\',\''.$field_id.'\');" alt="'.INF_REMOVE.'" title="'.INF_REMOVE.'"/>';
					$rp = '';
					$tab_rp = '';
					foreach ($inf['pattern'] as $k2 => $v2) {
						$p_fn = 'form_'.$v2['type'];

						if ($v2['type'] != 'money') {
							if ($_REQUEST['opt'] != 11) {
								$v2['addon_field'] = ' id="'.$field_id.'_Old'.$k2.'"'. ' ' .$v2['addon_field'];
							} else {
								$v2['addon_field'] = ' id="'.$field_id.$k2.'"'. ' ' .$v2['addon_field'];
							}
						}
						if (function_exists($p_fn)) {
							$fields_name = '';
							if ($v2['type'] == 'money') {
								$v2['default'] = array('money' => $v[$k2], 'currency' => $v[$k2.'_currency']);
							} else {
								$v2['default'] = $v[$k2];
							}

							if ($_REQUEST['opt'] == 11 || !isset($inf['multi']['spec'])) {
								$fields_name = $k2.'[]';
							} else {
								$fields_name = $k2.'_Old['.$k.']';
							}
							$f = $p_fn($fields_name, $v2).' ';
						} else {
							$f = $p_fn.'...';
						}
						$rp .= $f;
						$tab_rp .= '<td>'.$f.'</td>';
					}
					if ($v != '') {
						if ($_REQUEST['opt'] != 11) {
							$r .= '<div id="'.$field_id.'_Old'.$k.'">'.$rp.$del_botton.'</div>';
						} else {
							$r .= '<div id="'.$field_id.$k.'">'.$rp.$del_botton.'</div>';
						}
					}
					if ($_REQUEST['opt'] != 11) {
						$tab .= '<tr id="'.$field_id.'_Old'.$k.'" class="fw-event'.($row_c%2).'">'.$tab_rp.'<td>'.$del_botton.'</td></tr>';
					} else {
						$tab .= '<tr id="'.$field_id.$k.'" class="fw-event'.($row_c%2).'">'.$tab_rp.'<td>'.$del_botton.'</td></tr>';
					}
					$row_c++;
				}
				$tab .= '</table>';
			} else {
				$r .= '
				<script type="text/javascript">
					replicate_add_item("'.$field_id.'", "");
				</script>';
				$tab .= '</table>
				<script type="text/javascript">
					replicate_add_item("'.$field_id.'", "");
				</script>
				';
			}
			return $tab;
		}
	}
}

/**
 *
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * @return unknown_type
 */
function form_number($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'update':{
			$ret = prepare_number($post[$key], $inf);
			$post[$key] = $ret[0];
			$vl = $ret[1];
			$po[$key] = $post[$key];
			if ($basics['log_removed'] == 2 && ($post['opt'] == 4 || $_POST['opt4'])) {
				$qry .= '`'.$key.'`=NULL';
			} else {
				$qry .= '`'.$key.'`="'.$post[$key].'"';
			}
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			if ($inf['displayonly'] == 1) {
				if ($inf['default'] ) {
					$exp_num = explode('.', $inf['default']);
					$number = number_format($exp_num[0]);
					if ((double)$exp_num[1] > 0) {
						if (!$number) {
							$number = 0;
						}
						$number .= '.'.$exp_num[1];
					}
					return $number.$inf['append'];
				} else {
					return '';
				}
			}
			$inf['default'] = cleanForm($inf['default']);//cleanup data
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			} else {
				$readonly = '';
			}
			if ($inf['param2'] > 0) {
				$maxlen = ' maxlength="'.$inf['param2'].'"';
			} else {
				$maxlen = '';
			}
			if (!strstr(strtolower($inf['addon_field']), 'onkeypress') || !isset($inf['addon_field'])) {
				$inf['addon_field'] .= ' onKeyPress="return isNumberKey(event);"';
			}

			$width = 100;
			if ($inf['param2']) {
				$width = ($inf['param2']*8);
			} elseif ($inf['param1']) {
				$width = $inf['param1'];
			}
			$r = '<input type="text" name="'.$key.'" style="text-align: right; width: '.$width.'px;"'.$maxlen.$readonly.$inf['addon_field'].' value="'.$inf['default'].'" />';
			if (isset($inf['append'])) {
				$r .= $inf['append'];
			}
			return $r;
		}
	}
}

/**
 *
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * @return unknown_type
 */
function form_passw($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
			return;
		} break;
		case 'update':{
			if (strlen($post[$key]) > 0 && $post[$key] != 'no change') {
				if (++$lq != 1) {
					$qry .= ', ';
				}
				$po[$key] = md5($post[$key]);
				if ($basics['log_removed'] == 2 && ($post['opt'] == 4 || $_POST['opt4'])) {
					$qry .= '`'.$key.'`=NULL';
				} else {
					$qry .= '`'.$key.'`='.intoDB(md5($post[$key]), 'I').', ';
				}
			}
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			if ($inf['displayonly'] == 1) {
				return '**********';
			}
			$inf['default'] = cleanForm($inf['default']);//cleanup data
			$readonly = '';
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			}
			$style = ' style="width: '.$inf['param1'].'px;"';
			$value = 'no change';
		//	if ($_REQUEST['opt'] == 10 || !$_REQUEST['opt']) $value = ''; else $value = 'no change';
			if ($inf['param2'] == 'I') {
				$r = '<input type="text" name="'.$key.'"'.$style.$readonly.$inf['addon_field'].' value="'.$inf['default'].'" />';
			} else {
				$r = '<input type="password" name="'.$key.'"'.$style.$readonly.$inf['addon_field'].' value="'.$value.'" />';
			}
			return $r;
		}
	}
}

/**
 * new password function
 * @param $key
 * @param $inf
 * @param $post
 * @return unknown_type
 */
function form_password($key,$inf,$act='form',$post=''){
	switch($act) {
		case 'validate':{
			if ($inf['param2'] == 'I') {
				if (!isset($post[$key]) || $post[$key] == '') {
					return $key;
				}
			} else {
				if (!$_POST[$key]) {
					if (!$_POST[$key.'_show']) {
						return $key;
					}
				}
			}
			return false;
		} break;
		case 'update':{
			if(!$_POST[$key]) {
				$post[$key] = $_POST[$key.'_show'];
			}
			if ($inf['param2'] > 0) {
				$post[$key] = substr($post[$key],0,$inf['param2']);
			}
			if (strlen($post[$key]) > 0 && $post[$key] != 'no change') {
				if (++$lq != 1) {
					$qry .= ', ';
				}
				$po[$key] = md5($post[$key]);
				if ($basics['log_removed'] == 2 && ($post['opt'] == 4 || $_POST['opt4'])) {
					$qry .= '`'.$key.'`=NULL';
				} else {
					$qry .= '`'.$key.'`='.intoDB(md5($post[$key]), 'I').', ';
				}
			}
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			if ($inf['displayonly'] == 1) {
				return '**********';
			}
			$inf['default'] = cleanForm($inf['default']);//cleanup data

			$readonly = '';
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			}
			$style = ' style="width: '.($inf['param1']-40).'px;"';
			$value = 'no change';
			if ($inf['param2'] == 'I') {
				$r = '<input type="text" name="'.$key.'"'.$style.$readonly.$inf['addon_field'].' value="'.$inf['default'].'" />';
			} else {
				$typ_pass = '<input type="password"'.$style.' maxlength="'.$inf['param2'].'" value="'.$value.'" name="'.$key.'" onChange="$(this).prev().val($(this).val());" />';
				$typ_txt = '<input type="text"'.substr_replace($style, 'display:none;', -1).' maxlength="'.$inf['param2'].'" value="'.$value.'" onChange="$(this).next().val($(this).val());" name="'.$key.'_show"/>';
				$r = $typ_txt.$typ_pass.'&nbsp;<img style="cursor:pointer;" src="im/wand.png" onClick="password_set(this);" title="generate password" />&nbsp;<img style="cursor:pointer;" src="im/arrow_undo.png" onClick="password_toggle_show(this);" title="show/hide password"/>';
			}
			return $r;
		}
	}
}

/**
 * radio form without fw
 *
 * @param string $key - field name
 * @param array $inf - 'values' (array of data)
 * @param array $inf - 'default' (set default value)
 * @param array $inf - 'param1' (set separator between value)
 * @param array $inf - 'readonly'
 *
 * @example $company = array('1' => 'NSA','2' => 'NSSF');
 * @example form_radio('company',array('values' => $company, 'default' => 2,'param1' => '<br/>','readonly' => 0));
 *
 * @return string of radio form
 */
function form_radio($key, $inf, $act = 'form', $post = '', $id_prefix = ''){
	switch($act) {
		case 'validate':{
			if (trim($post[$key] == '') || !isset($post[$key])) return $key;
			return false;
		} break;
		case 'update':{
			$po[$key] = $post[$key];
			$qry = '`'.$key.'`='.intoDB($post[$key]);
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			if (!is_array($inf['values'])) {
				return;//don't return anything if we don't have values
			}
			if ($inf['displayonly'] == 1) {
				if (isset($inf['prepend'])) {
					$prepend = $inf['prepend'];
				}

				return $prepend.$inf['values'][$inf['default']];
			}
			$inf['default'] = cleanForm($inf['default']);//cleanup data
			$r = '';
			$readonly = '';
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			}
			$align = 'h';
			if ($inf['align']) {
				$align = $inf['align'];
			}
			if ($id_prefix != '') {
			    $id_prefix .= '-radio-'.$key;
			} else {
			    $id_prefix = 'radio-'.$key;
			}

			if (count($inf['values']) > 3 && $align == 'h' && $inf['force_radio'] != 1) {
				return form_select($key, $inf);
			}

			if (isset($inf['prepend'])) {
				$r .= $inf['prepend'];
			}

			//keep hidden fields for keep value
			if (count($inf['values']) == 1 && $inf['force_radio'] != 1) {
				$ky = array_keys($inf['values']);
				$vl = array_values($inf['values']);
				$r .= $vl[0].'<input type="hidden" name="'.$key.'" value="'.$ky[0].'"/>';
			} else {
				foreach ($inf['values'] as $ky => $vl) {
					$field_id = $id_prefix.'-'.$ky;
					$r .= '<p class="input_align_'.$align.'"><input id="'.$field_id.'" '.$readonly.$inf['addon_field'].' class="brd0" type="radio" name="'.$key.'" value="'.$ky.'"';
					if ($ky == $inf['default']) {
						$r .= ' checked';
					}
					$r .= ' />';
					$r .= '<label for="'.$field_id.'"> '.$vl.$inf['param1'].'&nbsp;</label></p>';
				}
			}

			//append data
			if (isset($inf['append'])) {
				$r .= $inf['append'];
			}

			return $r;
		}
	}
}

/**
 * textare form without fw
 *
 * @param string $key - field name
 * @param array $inf - 'default' (set of data)
 * @param array $inf - 'param1' (set [width:height] for textarea)
 * @param array $inf - 'param2' (select type of editor tool)
 * @param array $inf - 'values' ['skin'] && ['toolbar'] (set style of editor)
 * @param array $inf - 'readonly'
 *
 * @example form_textarea('company',array('values' => array('skin' => 1,'toolbar' => 1, 'default' => 2),'param1' => '400:400','readonly' => 0))
 *
 * @return string of textarea form
 */
function form_textarea($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'search_result':{
			return array(
				'cut' => 1,
			);
		} break;
		case 'update':{
			if ($inf['param2'] > 0) {
				$post[$key] = substr($post[$key], 0, $inf['param2']);
			}
			if ($inf['vhead'] && $post[$key] == $inf['vhead']) {
				$post[$key] = 'NULL';
			}
			$po[$key] = $post[$key];
			$qry = '`'.$key.'`='.intoDB($post[$key]);
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			$param1 = explode(':',$inf['param1']);
			$style = ' style="';
			if ($param1[0]) {
				$style .= 'width: '.$param1[0].'px;';
			}
			if ($param1[1]) {
				$style .= ' height: '.$param1[1].'px;';
			}
			$fullpage = '';
			if ($inf['fullpage'] == 1) {
				$fullpage = 'fullpage,';
			}
			$resize = '';
			if ($inf['resize'] == 'horizontal') {
				$resize = 'theme_advanced_resize_horizontal : 0,';
			}
			$cfbutton = '';
			if ($inf['cfbutton'] == 1) {
				$cfbutton = ',cfspecial';
			}
			//define path of ajaxfilemanager relative path only!!
			$path_dir = '';
			if ($inf['values']['dir']) {
				$path_dir = '?DIR_PATH='.$inf['values']['dir'];
			}
			$style .= '"';
                        $toolbar_default = 1;
                        $toolbar_opt = array(1 => 'theme_advanced_buttons1 : "formatselect,fontsizeselect,mylistbox,mysplitbutton,bold,italic,underline,strikethrough,separator,sub,sup,justifyleft,justifycenter,justifyright,justifyfull,|,forecolor,backcolor,|,cut,copy,paste,pastetext",
                                        theme_advanced_buttons2 : "bullist,numlist,undo,redo,link,unlink,anchor,image,cleanup,code,|,tablecontrols,fullscreen",
                                        theme_advanced_buttons3 : "",',
                                            2 => 'theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
						theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
						theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
						theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft'.$cfbutton.'",',
                                            3 => 'theme_advanced_buttons1 : "formatselect,fontsizeselect,bold,italic,underline,strikethrough,|,sub,sup,separator,justifyleft,justifycenter,justifyright,justifyfull",
                                                  theme_advanced_buttons2 : "cut,copy,paste,pastetext,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,|,anchor,image,cleanup,code",
                                                  theme_advanced_buttons3 : "",');
//                        theme_advanced_buttons3_add : "spellchecker",
                        if($inf['values']['toolbar']) {
                            $toolbar_opt_set = $toolbar_opt[$inf['values']['toolbar']];
                        } else {
                            $toolbar_opt_set = $toolbar_opt[$toolbar_default];
                        }
			$tinyMCE_script = '
					tinyMCE.init({
						mode : "exact",
						elements : "'.$key.'",
						theme : "advanced",
						plugins : "'.$fullpage.'spellchecker,pagebreak,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave'.$cfbutton.'",
//						plugins : "table,advhr,advimage,advlink,flash,paste,fullscreen,noneditable,contextmenu",
						relative_urls : true,
						remove_script_host : false,
						width:"'.$param1[0].'",
						height:"'.$param1[1].'",

						// Theme options
						'.$toolbar_opt_set.'
                                                spellchecker_languages : "+English=en",
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "left",
						theme_advanced_statusbar_location : "bottom",
						theme_advanced_resizing : true,
						theme_advanced_path: false,
						'.$resize.'
						file_browser_callback : "ajaxfilemanager",
						verify_html : false,
//						extended_valid_elements: "style",
						extended_valid_elements: "u|b|strong|font|style|meta|title|html|body|head",
						valid_elements : "*[*]",
						invalid_elements : "",
						remove_linebreaks : false,
						apply_source_formatting : false,
						relative_urls : false,
						remove_script_host : false,
						theme_advanced_path : false,
						// Example content CSS (should be your site CSS)
//						content_css : "css/content.css",
						force_p_newlines : false,
//						cleanup_callback : "Application.Modules.TinyMCE.customCleanup",
						// Drop lists for link/image/media/template dialogs
						template_external_list_url : "lists/template_list.js",
						external_link_list_url : "lists/link_list.js",
						external_image_list_url : "lists/image_list.js",
						media_external_list_url : "lists/media_list.js",
						// Style formats
						style_formats : [
							{title : \'Bold text\', inline : \'b\'},
							{title : \'Red text\', inline : \'span\', styles : {color : \'#ff0000\'}},
							{title : \'Red header\', block : \'h1\', styles : {color : \'#ff0000\'}},
							{title : \'Example 1\', inline : \'span\', classes : \'example1\'},
							{title : \'Example 2\', inline : \'span\', classes : \'example2\'},
							{title : \'Table styles\'},
							{title : \'Table row 1\', selector : \'tr\', classes : \'tablerow1\'}
						]
					});

					function ajaxfilemanager(field_name, url, type, win) {
						switch (type) {
							case "image":
								break;
							case "media":
								break;
							case "flash":
								break;
							case "file":
								break;
							default:
								return false;
						}
			            tinyMCE.activeEditor.windowManager.open({
			                url: "lib/editor/tiny_mce/plugins/ajaxfilemanager/ajaxfilemanager.php'.$path_dir.'",
			                width: 782,
			                height: 440,
			                inline : "yes",
			                close_previous : "no"
			            },{
			                window : win,
			                input : field_name
			            });
			            return false;
					}

					';
			if ($inf['displayonly'] == 1) {
				if ($inf['param2'] == 'T' && MCE == 1) {
					$jsscript = '<script type="text/javascript">'.$tinyMCE_script.'</script>';
				}
				$r = nl2br(htmlspecialchars($inf['default']));
				if ($inf['prepend'] && $inf['default']) {
					$r = $inf['prepend'].$r;
				}
				if ($inf['append'] && $inf['default']) {
					$r .= $inf['append'];
				}
				return $r.$jsscript;
			}
			$readonly = '';
			$r = '';
			$field_id = 'field_'.$key;
			if ($inf['readonly'] == 1) {
				$readonly = ' readonly';
			}
			if ($inf['param2'] == 'W' && WYM == 1) {
				static $wymIndex = -1;
				$inf['default'] = cleanForm($inf['default'], 3);//cleanup data
				$r = '
				<script type="text/javascript">
					wymData['.++$wymIndex.'] = "'.$inf['default'].'";
				</script>
				<textarea class="wymeditor" name="'.$key.'"'.$style.'></textarea>';
			} else if ($inf['param2'] == 'T' && MCE == 1) {
				$inf['default'] = cleanForm($inf['default']);//cleanup data
				$mce_tool = array('1' => 'advanced', '2' => 'simple');
				$mce_skin = array('1' => 'default', '2' => 'o2k7');
				if ($inf['values']['skin']) {
					$skin = 'skin : "'.$mce_skin[$inf['values']['skin']].'",';
				}
				$r .= '
				<textarea id="'.$key.'" name="'.$key.'" class="mceajax">'.$inf['default'].'</textarea>
				<script type="text/javascript">
				'.$tinyMCE_script.'
				$(document).ready(function(){
					$("input[name=opt1], input[name=opt2]").click(function(){
						$("textarea[name='.$key.']").val(tinyMCE.get("'.$key.'").getContent());
					});
				});
				</script>';
			} else {
				if ($inf['elastic']) {
					$inf['addon_field'] .= ' class="elastic"';
				}
				$inf['default'] = cleanForm($inf['default']);//cleanup data
				if ($inf['vhead']) {
					$title = 'title="'.$inf['vhead'].'"';
				}
				if ($inf['param2'] > 0) {
					$inf['addon_field'] .= ' onkeyup="return imposeMaxLength(this, '.$inf['param2'].');"';
				}
				$r = '<textarea name="'.$key.'"'.$style.$readonly.$inf['addon_field'].$title.'>'.$inf['default'].'</textarea>';
			}
			return $r;
		}
	}
}

/**
 * create time range 00:00 - 00:00
 *
 * @param string $key
 * @param array $inf
 * @return form_time_range('shift',array('param2' => array('H' => '0:11','I' => '15'),'default' => '09:30','readonly' => 0));
 */
function form_time_range($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
			if (trim($post[$key.'_from_calendar']) == '' || trim($post[$key.'_to_calendar']) == '') {
				return $key;
			}
			return false;
		} break;
		case 'update':{
			if ($vl['values'] == 'time') {
				if ($post[$key.'_from'][0] == '00:00') {
					$post[$key.'_from'][0] = NULL;
				} else {
					$post[$key.'_from'][0] = $post[$key.'_from'][0].':00';
				}
				if ($post[$key.'_to'][0] == '00:00') {
					$post[$key.'_to'][0] = NULL;
				} else {
					$post[$key.'_to'][0] = $post[$key.'_to'][0].':00';
				}
			} else if ($vl['values'] == 'date') {
				if ($post[$key.'_from_calendar'] == '') {
					$post[$key.'_from'][0] = NULL;
				} else {
					$post[$key.'_from'][0] = date('Y-m-d', strtotime($post[$key.'_from_calendar']));
				}
				if ($post[$key.'_to_calendar'] == '') {
					$post[$key.'_to'][0] = NULL;
				} else {
					$post[$key.'_to'][0] = date('Y-m-d', strtotime($post[$key.'_to_calendar']));
				}
			}
			$po[$key.'_from'] = $post[$key.'_from'][0];
			$po[$key.'_to'] = $post[$key.'_to'][0];
			if ($basics['log_removed'] == 2 && ($post['opt'] == 4 || $_POST['opt4'])) {
				$qry .= '`'.$key.'_from`=NULL,`'.$key.'_to`=NULL';
			} else {
				$qry .= '`'.$key.'_from`="'.$post[$key.'_from'][0].'",`'.$key.'_to`="'.$post[$key.'_to'][0].'"';
			}
		} break;
		default:{
			if ($inf['arr'] == 1) {
				$key1 = $key.'_from[]';
				$key2 = $key.'_to[]';
			} else {
				$key1 = $key.'_from';
				$key2 = $key.'_to';
			}
			if ($inf['default'][0] == '0000-00-00') {
				$inf['default'][0] = '';
			}
			if ($inf['default'][1] == '0000-00-00') {
				$inf['default'][1] = '';
			}

			if ($inf['values'][0] == 'time') {
				$r = form_date($key1, array('values' => 'datetime', 'param1' => 'hi', 'param2' => array('H' => $inf['param2']['H'], 'I' => $inf['param2']['I']), 'default' => $inf['default'][0], 'readonly' => $inf['readonly'], 'displayonly' => $inf['displayonly'], 'addon_field' => $inf['addon_field']));
				$r .= ' - ';
				$r .= form_date($key2, array('values' => 'datetime', 'param1' => 'hi', 'param2' => array('H' => $inf['param2']['H'], 'I' => $inf['param2']['I']), 'default' => $inf['default'][1], 'readonly' => $inf['readonly'], 'displayonly' => $inf['displayonly'], 'addon_field' => $inf['addon_field']));
			} else if ($inf['values'][0] == 'date') {
				$r = form_date($key1, array('values' => 'date', 'param1' => 'dmy', 'values' => 'date', 'default' => $inf['default'][0], 'readonly' => $inf['readonly'], 'displayonly' => $inf['displayonly'], 'addon_field' => $inf['addon_field']));
				$r .= '&nbsp;&nbsp;&nbsp;';
				$r .= form_date($key2, array('values' => 'date', 'param1' => 'dmy', 'values' => 'date', 'default' => $inf['default'][1], 'readonly' => $inf['readonly'], 'displayonly' => $inf['displayonly'], 'addon_field' => $inf['addon_field']));
			}
			return $r;
		}
	}
}

/**
 * create multi for multi custom function
 *
 * @param string $key
 * @param array $inf
 * @example set loop for id_hub.. for each hubs need array
 * @example form_E_multi('fixed_routes-'.$id_hub,array('H' => $lng['fixed_routes'], 'multi' => array('multi' => 'Z'), 'show' => 1, 'skip' => 1);
 * @return
 */
function form_E_multi($key, $inf){
	$id_key = '';
	$show_ = array();
	if (strstr($key, '-')) {
		$fn_name = explode('-', $key);
		$key 	 = $fn_name[0];
		$id_key = $fn_name[1];
	}

	$field_id = 'field_'.$key;
	if ($id_key != '') {
		$field_id .= '-'.$id_key;
	}
	//$cf_name = 'cf_'.$key;
	$cf_name = PREFIX.$_REQUEST['mod'].'_'.$key;
	$show_ = $cf_name($inf,'show',$_REQUEST['id']);
	$r = '<div id="'.$field_id.'_0" style="display: none;">'.$show_['model'].'</div>';
	if (is_array($show_['default'])) {
		foreach ($show_['default'] as $id => $inf_) {
			$r .= '<div id="'.$field_id.$id.'">'.$inf_.' <img src="im/remove.png" onclick="replicate_remove_item(\''.$field_id.$id.'\',\''.$field_id.'\');" /></div>';
		}
	} else {
		//for dropdown... cf
		if ($inf['conv'] == 1)	{
			$r .= $show_['conv'];
		} else {
		$r .= '
			<script type="text/javascript">
				replicate_add_item("'.$field_id.'","");
			</script>';
		}
	}
	return $r;
}

/**
 * form_time_range_multi with out fw
 *
 * @param string $key
 * @param array $inf
 * @return
 * $multi = array('multi' => 'X','qry_col_value' => 'break_time', 'qry_tab' => 'break_time','qry_col_check' => 'id_hub');
 *	$fields['break'] = array('H' => 'Break','T' => 'TRM','multi' => $multi,'param2' => array('H' => '0:11','I' => '15'),'default' => '09:30','readonly' => 0);
 */
function form_time_range_multi($key, $inf, $act = 'form', $post = ''){
	//name for fields
	$field_id = 'field_'.$key;
	//set pattern for duplicate input fields
	$r = '<div id="'.$field_id.'_0" style="display: none;">'.form_time_range($key, $inf).'</div>';
	if (is_array($inf['default']) && count($inf['default']) > 0) {
		$inf['default'] = cleanForm($inf['default']);//cleanup data
		foreach ($inf['default'] as $k => $v) {
			$del_botton = ' <img src="im/remove.png" class="fw-point" onclick="replicate_remove_item(\''.$field_id.'_'.($k+1).'\',\''.$field_id.'\');" alt="'.INF_REMOVE.'" title="'.INF_REMOVE.'"/>';
			//set array for get default value
			$inf_ = $inf;
			$inf_['default'] = array_values($v);
			if ($v != '') {
				$r .= '<div id="'.$field_id.'_'.($k+1).'">'.form_time_range($key,$inf_).$del_botton.'</div>';
			}
		}
	} else {
		$r .= '
		<script type="text/javascript">
			replicate_add_item("'.$field_id.'","");
		</script>';
	}
	return $r;
}

/**
 * date form with out fw
 *
 * @param string $key
 * @param array $inf - 'values' set type of date {unix, date, time,datetime}
 * @param array $inf - 'param1' display for date form {'dmy', 'd', 'dm',...}
 * @param array $inf - 'param2' set range for value
 * @example form_date('open_day',array('values' => 'datetime','param1' => 'myi','param2' => array('Y' => '2001:2010','I' => '5')))
 * @return string of date form
 */
function form_date($key, $inf, $act = 'form', $post = ''){
	$js_separate = CALENDAR_JS_SEPARATE;
	switch($act) {
		case 'search_result':{
			if ($inf['values'] == 'date' || $inf['values'] == 'datetime') {
				return array(
					'format_date' => array(
						$_SESSION[SESSION_A]['format_date'] => date($_SESSION[SESSION_A]['format_date']),
						$_SESSION[SESSION_A]['format_date'] . ' ' . $_SESSION[SESSION_A]['format_time'] => date($_SESSION[SESSION_A]['format_date'] . ' ' . $_SESSION[SESSION_A]['format_time']),
						'd M' => date('d M'),
						'd F' => date('d F'),
					),
				);
			}
		} break;
		case 'validate':{
			$inf['param1'] = strtolower($inf['param1']);
			if (strstr($inf['param1'], 'd') && strstr($inf['param1'], 'm') && strstr($inf['param1'], 'y')) {
				if ($inf['param2'] == '') {
					if (empty($post[$key . '_calendar'])) {
						++$date_err;
					}
				} else {
					if (empty($post[$key.'_day'])) {
						++$date_err;
					}
					if (empty($post[$key.'_month'])) {
						++$date_err;
					}
					if (empty($post[$key.'_year'])) {
						++$date_err;
					}
				}
			}
			if (strstr($inf['param1'], 'i') && strstr($inf['param1'], 'h')) {
				if ($inf['param2'] == '') {
					if (empty($post[$key . '_time'])) {
						++$date_err;
					}
				} else {
					if ($inf['values'] == 'time') {
						if (empty($post[$key])) {
							++$date_err;
						}
					} else {
						if (empty($post[$key . '_hour'])) {
							++$date_err;
						}
						if (empty($post[$key . '_min'])) {
							++$date_err;
						}
					}
				}
			}

			if ($date_err > 0) {
				return $key;
			}
			return false;
		} break;
		case 'update':{
			$date = '0000' . $js_separate{0} . '00' . $js_separate{0} . '00';
			$time = '00' . $js_separate{1} . '00' . $js_separate{1} . '00';
			if (isset($post[$key . '_calendar'])) {
				if ($post[$key . '_calendar'] != '') {
					$date = date('Y-m-d', strtotime($post[$key . '_calendar']));
				}
			} else {
				$year = date('Y');
				$month = $day = '00';
				if ($post[$key . '_year'] != '') {
					$year = $post[$key . '_year'];
				}
				if ($post[$key . '_month'] != '') {
					$month = $post[$key . '_month'];
				}
				if ($post[$key . '_day'] != '') {
					$day = $post[$key . '_day'];
				}
				if ($month != '00' && $day != '00') {
					$date = $day . ' '. $month . ' ' . $year;
					$date = date('Y-m-d', strtotime($date));
				}
			}

			//time picker
			if (isset($post[$key . '_time'])) {
				if ($post[$key . '_time'] != '') {
					$time = date('H:i:s', strtotime('2011-01-01 ' . $post[$key . '_time']));
				}
			} else if (isset($post[$key])) {
				$time = $post[$key] . ':00';
			} else {
				$hour = $minute = '00';
				if ($post[$key . '_hour'] != '') {
					$hour = $post[$key . '_hour'];
				}
				if ($post[$key.'_minute'] != '') {
					$minute = $post[$key.'_minute'];
				}

				$time = $hour . $js_separate{1} . $minute . $js_separate{1} . '00';
			}

			if ($date != '0000' . $js_separate{0} . '00' . $js_separate{0} . '00' && $time != '00' . $js_separate{1} . '00' . $js_separate{1} . '00') {
				$post[$key] = $date . ' ' . $time;
			} else {
				$post[$key] = 'NULL';
			}

			if ($inf['values'] == 'timestamp' || $inf['values'] == 'datetime') {
			} else if ($inf['values'] == 'date') {
				$post[$key] = $date;
			} else if ($inf['values'] == 'time') {
				$post[$key] = $time;
			} else if ($inf['values'] == 'year') {
				$post[$key] = $year;
			} else {
				$post[$key] = strtotime($post[$key]);
			}
			$po[$key] = $post[$key];

			$qry = '`' . $key . '`=' . intoDB($post[$key]);
			return array('qry' => $qry, 'po' => $po);
		} break;
		default: {
			$js_separate = CALENDAR_JS_SEPARATE;
			$inf['default'] = cleanForm($inf['default']);//cleanup data
			//pass id from request if want to fixed array
			$pass_id = '';
			if ($_REQUEST['pass_id']) {
				$pass_id = $_REQUEST['pass_id'];
			}
			$pass_id2 = '';
			if ($_REQUEST['pass_id2']) {
				$pass_id2 = $_REQUEST['pass_id2'];
			}
			//set all to unix time
			//make lowercase so we can compare faster
			$inf['param1'] = strtolower($inf['param1']);

			if ($inf['values'] == 'year') {
				//$inf['default'] = $inf['default'] . '-01-01';
			}

			if ($inf['param1'] != 'hi' && $inf['param1'] != 'y') {
				if (($inf['values'] != 'unix' || !isset($inf['values'])) && $inf['default'] != 0 && $inf['values'] != 'number') {
					$inf['default'] = date_fix_format($inf['default']);
					$inf['default'] = strtotime($inf['default']);
				}
			}

			if ($inf['default'] == '0000-00-00 00:00:00' || $inf['default'] == '0000-00-00' || $inf['default'] == '00:00:00') {
				$inf['default'] = '';
			}

			if ((strstr($inf['param1'], 'd') && strstr($inf['param1'], 'm') && strstr($inf['param1'], 'y')) || $inf['param1'] == '') {
				$calendar = '';
				if ($inf['default']) {
					$calendar = date(translate_date(CALENDAR_JS_FORMAT), $inf['default']);
				}
			} else {
				$sep = CALENDAR_DAY_MONTH_YEAR;
				if (strstr(strtolower($inf['param1']), 'd')) {
					$days[] = '';
					for ($i = 1; $i < 32; $i++) {
						if (strlen($i) == 1) {
							$j = '0'.$i;
						} else {
							$j = $i;
						}
						$days[] = $j;
					}
					if ($inf['default']) {
						$day = date($sep{0}, $inf['default']);
					} else {
						$day = '';
					}
				}
				if (strstr(strtolower($inf['param1']), 'm')) {
					$months[] = '';
					for ($i = 0; $i < 12; $i++) {
						$months[] = date($sep{1}, strtotime('15 January ' . date('Y') . ' + ' . $i . ' months'));
					}
					if ($inf['default']) {
						$month = date($sep{1}, $inf['default']);
					} else {
						$month = '';
					}
				}
				if (strstr(strtolower($inf['param1']), 'y')) {
					$years[] = '';
					if ($inf['req'] == 1) {
						$years = array();
					}
					if (isset($inf['param2']['Y'])) {
						$mm = explode(':', $inf['param2']['Y']);
						if ($inf['re-order']) {
							for ($i = $mm[1]; $i > $mm[0]-1; $i--) {
								$years[] = $i;
							}
						} else {
							for ($i = $mm[0]; $i < $mm[1] + 1; $i++) {
								$years[] = $i;
							}
						}
					} else {
						$years[] = date('Y');
					}
					if ($inf['default']) {
						if ($inf['values'] == 'year') {
							$year = $inf['default'];
						} else {
							$year = date($sep{2}, $inf['default']);
						}
					} else {
						$year = '';
					}
				}
			}

			//time
			if (strstr($inf['param1'], 'h') && strstr($inf['param1'], 'i')) {
				if ($inf['param2'] == '') {
					$timepicker = '';
					if ($inf['default']) {
						if ($inf['values'] == 'time') {
							$timepicker = date('h:i A', strtotime('2011-02-15 ' . $inf['default']));
						} else if ($inf['values'] == 'datetime') {
							$timepicker = date('h:i A', $inf['default']);
						}
					}
				} else {
					//check I
					if ($inf['param2']['I'] > 0) {
						$switch = $inf['param2']['I'];
					} else {
						$switch = 1;
					}
					$minutes[] = '';
					for ($i = 0; $i < 60; $i+=$switch) {
						if (strlen($i) == 1) {
							$j = '0'.$i;
						} else {
							$j = $i;
						}
						$minutes_[] = $j;
					}
					//check H
					$hours[] = '';
					if (strstr($inf['param2']['H'], ':')) {
						$mm = explode(':', $inf['param2']['H']);
					} else {
						$mm = array(0, 23);
					}
					for ($i = $mm[0]; $i < $mm[1]+1; $i++) {
						if (strlen($i) == 1) {
							$j = '0'.$i;
						} else {
							$j = $i;
						}
						$hours_[] = $j;
					}

					foreach ($hours_ as $k => $hr) {
						if ((int)$hr == $mm[1]) {
							$time_range[] = $hr . ':00';
						} else {
							foreach ($minutes_ as $k1 => $min) {
								$time_range[] = $hr . ':' . $min;
							}
						}
					}

					if ($inf['default']) {
						$time_range_d = substr($inf['default'],0,-3);
					} else {
						$time_range_d = '';
					}
				}
			} else {
				if (strstr(strtolower($inf['param1']), 'i')) {
					if ($inf['param2']['I'] > 0) {
						$switch = $inf['param2']['I'];
					} else {
						$switch = 1;
					}
					$minutes[] = '';
					for ($i = 0; $i < 60; $i += $switch) {
						if (strlen($i) == 1) {
							$j = '0'.$i;
						} else {
							$j = $i;
						}
						$minutes[] = $j;
					}
					if ($inf['default']) {
						if ($inf['values'] == 'time') {
							$minute = substr($inf['default'], -2);
						} else if ($inf['values'] == 'number') {
							$minute = $inf['default'];
						} else {
							$minute = date('i', $inf['default']);
						}

						if ($switch != 1) {
							$minute = ceil($minute/$switch) * $switch;
							if ($minute == 60) {
								$minute = 0;
								$hour_up = 1;
							}
						}
					} else {
						$minute = '';
					}
					if ($inf['param2']['unit']['I']) {
						$unit['I'] = $inf['param2']['unit']['I'];
					} else {
						$unit['I'] = '';
					}
				}

				if (strstr($inf['param1'], 'h')) {
					$hours[] = '';
					if (strstr($inf['param2']['H'], ':')) {
						$mm = explode(':', $inf['param2']['H']);
					} else {
						$mm = array(0, 23);
					}
					for($i=$mm[0]; $i<$mm[1]+1; $i++) {
						if (strlen($i) == 1) {
							$j = '0'.$i;
						} else {
							$j = $i;
						}
						$hours[] = $j;
					}

					if ($inf['default']) {
						if ($inf['values'] != 'number') {
							$hour = date('H', $inf['default']);
						} else {
							$hour = $inf['default'];
						}
						if ($hour_up == 1) {
							(int)$hour += 1;
						}
					} else {
						$hour = '';
					}

					if ($inf['param2']['unit']['H']) {
						$unit['H'] = $inf['param2']['unit']['H'];
					} else {
						$unit['H'] = '';
					}
				}
			}

			if ($inf['readonly'] == 1) {
				if (isset($calendar)) {
					$r = '<input type="text" class="jsdate" name="' . $key . '_calendar" ' . $inf['addon_field'] . ' readonly style=" width: 100px;" value="'.$calendar.'"/> ';
				}
				if (isset($timepicker)) {
					$r .= '<input type="text" class="jsdate" name="' . $key . '_time" ' . $inf['addon_field'] . ' readonly style=" width: 55px;" value="'.$timepicker.'"/>';
				}
				if (isset($years)) {
					$r .= '<input '.$inf['addon_field'].' readonly type="text" style="width: 30px" name="'.$key.'_year" value="'.$year.'" />';
				}
				if (isset($months)) {
					$r .= ' ';
					if (isset($years)) {
//						$r .= $js_separate{0};
					}
					$r .= '<input '.$inf['addon_field'].' readonly type="text" style="width: 20px" name="'.$key.'_month" value="'.$month.'" />';
				}
				if (isset($days)) {
					$r .= ' ';
					if (isset($months) || isset($years)) {
//						$r .= $js_separate{0};
					}
					$r .= '<input '.$inf['addon_field'].' readonly type="text" style="width: 20px" name="'.$key.'_day" value="'.$day.'" />';
				}

				if (isset($time_range)) {
					$r .= '<select '.$inf['addon_field'].' disabled name="'.$key.'">'.array_norm($time_range,$time_range_d).'</select>';
				} else {
					if (isset($hours)) {
						$r .= ' <input '.$inf['addon_field'].' readonly type="text" style="width: 20px" name="'.$key.'_hour" value="'.$hour.'" />';
					}
					if (isset($minutes)) {
						$r .= ' ';
						if (isset($hours)) {
//							$r .= $js_separate{1};
						}
						$r .= '<input '.$inf['addon_field'].' readonly type="text" style="width: 20px" name="'.$key.'_minute['.$pass_id.']" value="'.$minute.'" />';
					}
				}
			// readonly;
			} else {
				//TODO set value to array for all type now i change only minute //BEEM
				if (isset($calendar)) {
					$pattern = "!(\[(.*)\])!Uis";
					preg_match($pattern, $key, $matches);
					if ($matches) {
						$calendar_name = str_replace($matches[0], '', $key).'_calendar' . $matches[0];
					} else {
						$calendar_name = $key.'_calendar';
					}
					$sortable_value = '';
					if ($inf['sortable'] == 1 && $inf['default']) {
						$sortable_value = '<span class="hide">'.$inf['default'].'</span>';
					}
					if ($inf['displayonly'] == 1) {
						$r = $sortable_value.$calendar;
					} else {
						$r = '<input type="text" class="jsdate" '.$inf['addon_field'].' style=" width: 100px;" name="'.$calendar_name.'" value="'.$calendar.'"/> ';
					}
				}

				if (isset($timepicker)) {
					if ($inf['displayonly'] == 1) {
						$r .= ' ' . $timepicker;
					} else {
						$style = ' style="width: 55px;';
						if ($inf['addon_style']) {
							$style .= $inf['addon_style'];
						}
						$style .= '"';
						$r .= '<input type="text" class="jstime" '.$inf['addon_field'] . $style . ' name="' . $key . '_time" value="' . $timepicker . '"/>';
					}
				}

				if (isset($years)) {
					if ($inf['displayonly'] == 1) {
						$r .= ' '.$year;
					} else {
						if ($inf['disabled'] == 1) {
							$inf['addon_field'] .= ' disabled';
						}
						$r = '<select '.$inf['addon_field'].' name="'.$key.'_year">'.array_norm($years, $year).'</select>';
					}
				}
				if (isset($days)) {
					if ($inf['displayonly'] == 1) {
						$r .= ' '.$day;
					} else {
						$r .= ' ';
						if (isset($months) || isset($years)) {
//							$r .= $js_separate{0};
						}
						$r .= '<select '.$inf['addon_field'].' name="'.$key.'_day">' . array_norm($days, $day) . '</select>';
					}
				}
				if (isset($months)) {
					if ($inf['displayonly'] == 1) {
						$r .= ' '.$month;
					} else {
						$r .= ' ';
						if (isset($years)) {
//							$r .= $js_separate{0};
						}
						$r .= '<select '.$inf['addon_field'].' name="'.$key.'_month">' . array_norm($months, $month) . '</select>';
					}
				}

				//change name for fields
				//$pass_id is request variable we got it from cf
				if ($pass_id != '') {
					$pass_name = $key.'['.$pass_id.']['.$pass_id2.']';
				} else {
					$pass_name = $key;
				}

				if (isset($time_range)) {
					if ($inf['displayonly'] == 1) {
						$r .= ' '.$time_range_d;
					} else {
						$r .= '<select '.$inf['addon_field'].' name="'.$pass_name.'">'.array_norm($time_range, $time_range_d).'</select>';
					}
				} else {
					if (isset($hours)) {
						if ($inf['displayonly'] == 1) {
							$r .= ' '.$hour;
						} else {
							$r .= ' <select '.$inf['addon_field'].' name="'.$key.'_hour">'.array_norm($hours, $hour).'</select> '.$unit['H'];
						}
					}
					if (isset($minutes)) {
						if ($inf['displayonly'] == 1) {
							$r .= ' '.$minute;
						} else {
							$r .= ' ';
							if (isset($hours)) {
								//$r .= $js_separate{1};
							}
							//'.$pass_name.'
							$r .= '<select '.$inf['addon_field'].' name="'.$key.'_minute">'.array_norm($minutes, $minute).'</select> '.$unit['I'];
						}
					}
				}
			}
			if ($inf['append']) {
				$r .= $inf['append'];
			}
			return $r;
		}
	}
}

/**
 * create upload multi file
 *
 * @param string $key
 * @param array $inf-
 * @return unknown
 */
function form_file_multi($key, $inf, $act = 'form', $post = ''){
	if ($inf['displayonly'] == 1) {
		return $inf['default'];//TODO this have to be redone
	} else {
		$style = '';
		$field_id = 'field_'.$key;

		$path = str_replace('{id}', $inf['id'], $inf['param2']['bigl']);
		if ($inf['readonly'] == 1) {
			$readonly = ' readonly';
		}
		if (!isset($inf['param2']['descr'])) {
			$inf['param2']['descr'] = 0;
		}
		if (!isset($inf['param2']['mini'])) {
			$inf['param2']['mini'] = 0;
		}

		if ($inf['param1']) {
			$style = ' size="'.$inf['param1'].'"';
			$txtstyle = ' style="width: '.($inf['param1']*8).'px;"';
		}

		//pattern
		$r = '<div id="'.$field_id.'_0" style="display: none;">
		<input type="file"'.$style.$inf['addon_field'].' name="'.$key.'_new[]" id="{id}"/>
		</div>';
		if (is_array($inf['default']) && count($inf['default']) > 0) {
			foreach ($inf['default'] as $id => $ext) {
				$gallery = $id.'.'.$ext;
				$link = $path.$gallery;
				$file = '';
				$remove = ' <img src="im/remove.png" onclick="replicate_remove_item(\''.$field_id.'_'.$id.'\',\''.$field_id.'\')" class="remove" alt="'.msg(INF_REMOVE).'" title="'.msg(INF_REMOVE).'"/>';
				if (is_file($link)) {
					$file = ' <a href="'.$link.'" target="_blank"><img src="'.FRAMEWORK_IMG.'file_download.png"/></a>';
				}
				$r .= '<div class="marginTop5px">'.$file.' <input type="file"'.$style.$inf['addon_field'].' name="'.$key.'_Old['.$id.']" id="'.$field_id.'_'.$id.'"/><input type="hidden" name="'.$key.'_files['.$id.']" >'.$remove.'</div>';
			}
		} else {
			$r .= '	<script type="text/javascript">replicate_add_item(\''.$field_id.'\');</script>';
		}
		return $r;
	}
}

/**
 * Enter description here...
 *
 * @param string $key-name of fields
 * @param array $inf-array for define values
 * @param string $link-link for image
 *
 * @example array('H' => $lng['picture'], 'T' => 'F', 'param2' => array('bigl' => 'files/user_picture/', 'name' => 'E'), 'values' => array('jpg', 'jpeg', 'gif'));
 * @return file fields
 */
function form_file($key, $inf, $link = '', $act = 'form', $post = '', $basics = ''){
	switch($act) {
		case 'validate':{
			if (!$_FILES[$key]) {
				if (!$_POST[$key . '_default']) {
					return $key;
				}
			}
			return false;
		} break;
		case 'update':{
			if ($post['merge'] == 1) {
				//check file exist
				$file_name = '';
				$file_ext = $post[$key]['file'];
				$par = $inf['param2'];
				if ($file_ext) {
					if ($par['name'] == 'N') {
						$name = $post['id'].'_'.$key.'.'.$file_ext;//id_field_name
						$new_name = $post['id_item_update'].'_'.$key.'.'.$file_ext;//id_field_name
					} else if ($par['name'] == 'E') {
						$name = $post['id'].'.'.$file_ext;//use id for file name
						$new_name = $post['id_item_update'].'.'.$file_ext;//use id for file name
					} else if ($inf['param2']['name'] == 'F') { //set fields
						$name = $_POST[$inf['param2']['fields']].'.'.$file_ext;//use id for file name
						$new_name = $_POST[$inf['param2']['fields']].'.'.$file_ext; //TODO
					}

					$qry = '';
					$big_link = $par['bigl'].$name;//name of file
					if (file_exists($par['bigl'] . $new_name)) {//remove original file before renaming old file
						unlink($par['bigl'] . $new_name);
					}
					if (file_exists($par['bigl'] . $name)) {
						rename($par['bigl'] . $name, $par['bigl'] . $new_name);
						//update file ext
						$qry .= SQL('`'.$key.'`=%s', $file_ext);
					} else {//if file does not exist then remove reference
						$qry .= '`'.$key.'`=""';
					}
					return array('qry' => $qry);
				} else {
					$qry .= SQL('`'.$key.'`=NULL');
					return array('qry' => $qry);
				}
			} else {
				$par = $inf['param2'];
				if (is_array($par)) {
					//set default values if empty
					if (!isset($par['bigd'])) {
						$par['bigd'] = '';
					}
					if (!isset($par['mini'])) {
						$par['mini'] = 0;
					}
					if (!isset($par['smld'])) {
						$par['smld'] = '';
					}
					if (!isset($par['ratio'])) {
						$par['ratio'] = 1;
					}
					if (!isset($_FILES[$key.'_s'])) {
						$_FILES[$key.'_s'] = '';
					}
					$sml_link = '';
					$sml_ext = '';

					if ($_POST['opt2'] && $inf['param2']['name'] == 'F' && !$_FILES[$key.'_b']) {
						$big_ext = $_POST['icon_default'];
					} else {
						$big_ext = strtolower(substr($_FILES[$key.'_b']['name'], strrpos($_FILES[$key.'_b']['name'], '.')+1));
					}

					if ($par['name'] == 'N') {
						$name = $basics['id'].'_'.$key.'.'.$big_ext;//id_field_name
						$post[$key] = $big_ext;
					} else if ($par['name'] == 'E') {
						$name = $basics['id'].'.'.$big_ext;//use id for file name
						$post[$key] = $big_ext;
					} else if ($inf['param2']['name'] == 'F') { //set fields
						$name = $_POST[$inf['param2']['fields']].'.'.$big_ext;//use id for file name
						$post[$key] = $big_ext;
					} else {
						$name = md5($_FILES[$key.'_b']['tmp_name'].time()).'.'.$big_ext;//random file name
						$post[$key] = $name;
					}

					$big_link = $par['bigl'].$name;//name of file
					if ($par['mini'] == 1) {
						$sml_ext = strtolower(substr($_FILES[$key.'_s']['name'], strrpos($_FILES[$key.'_s']['name'],'.')+1));
						$sml_link = $par['smll'].$name.'.'.$big_ext;
					} else if ($par['mini'] == 2) {
						$sml_ext = $big_ext;
						$sml_link = $par['smll'].$name;
					}

					if ($_POST['opt2'] && $inf['param2']['name'] == 'F' && !$_FILES[$key.'_b']) {
						//rename
						$old_file = $_POST['old_file_name'];
						$new_file = $par['bigl'] . $name;
						if (rename($old_file, $new_file)) {
							$po[$key] = $post[$key];
							$qry .= '`'.$key.'`=' . intoDB($post[$key], 'I') . ', ';
						} else {
							$qry .= '`'.$key.'`= NULL, ';
						}
					} else {
						if (file_upl($big_link, $_FILES[$key.'_b'], $big_ext, $par['bigd'], $inf['values'], $par['mini'], $sml_link, $_FILES[$key.'_s']) == 1) {
							if (++$lq != 1) {
								$qry .= ', ';
							}
							$po[$key] = $post[$key];
							$qry .= '`'.$key.'`='.intoDB($post[$key], 'I').', ';
						} else if (!$post[$key.'_default']) {
							$qry .= '`'.$key.'`= NULL, ';
						}
					}

					if ($par['descr'] == 1) {
						$po[$key.'_descr'] = $post[$key.'_descr'];
						if (!$qry) {
							$qry .= ', ';
						}
						$qry .= '`'.$key.'_descr`='.intoDB($post[$key.'_descr'], 'I').', ';
					}
				} else {
					$entity = $basics['entity'];
					$id = $basics['id'];
					$table = $basics['table'];
					if ($_FILES[$key]) {
						//get file name
						$file_name = fw_file_filter_name(fw_file_name($_FILES[$key]['name']));
						$upload_info = fw_file_upload_2($entity, $id, $key, $inf['path']);
						if (!$upload_info['error']) {
							$m_name = $upload_info['name'];
							$ext = fw_file_extension($_FILES[$key]['name']);
							$k_name = $m_name . '.' . $ext;//keep to file_name

							$param_qry = array(
								'table' => $table,
								'cols' => array(
									$key.'_updated', '', 'NOW()',
									$key.'_updated_by', '%d', $_SESSION[SESSION_L],
									$key, '%s', $k_name,
								),
								'where' => SQL($basics['key'].'=%d', $id),
							);
							db_query($param_qry);
						} else if (!$post[$key.'_default']) {
							$param_qry = array(
								'table' => $table,
								'cols' => array(
									$key.'_updated', '', 'NULL',
									$key.'_updated_by', '', 'NULL',
									$key, '', 'NULL',
								),
								'where' => SQL($basics['key'].'=%d', $id),
							);
							db_query($param_qry);
						}
					} else if (!$post[$key.'_default']) {
						$param_qry = array(
							'table' => $table,
							'cols' => array(
								$key.'_updated', '', 'NULL',
								$key.'_updated_by', '', 'NULL',
								$key, '', 'NULL',
							),
							'where' => SQL($basics['key'].'=%d', $id),
						);
						db_query($param_qry);
					}
				}
				return array('qry' => $qry, 'po' => $po);
			}
		} break;
		default:{
			if ($inf['displayonly'] == 1) {//TODO not tested
				//new
				if (!is_array($inf['param2'])) {
					
					//return icon download and preview
					return form_file_preview($key, $basics, $inf);
				} else {
					if ($inf['default']['file']) {
						$img_ext = array('jpg', 'jpeg', 'png', 'bmp', 'gif');
						if (in_array($inf['default']['file'], $img_ext)) {
							$file_pic = FRAMEWORK_IMG.'file_preview.png';
						} else {
							$file_pic = FRAMEWORK_IMG.'file_download.png';
						}
						$link = $inf['param2']['bigl'];
						if ($inf['param2']['name'] == 'E') {
							$link .= $inf['id'] . '.' . $inf['default']['file'];
						}
						if (file_exists($link)) {
							if ($inf['value_only'] == 1 && $_REQUEST['view'] != 'merge') {
								return '+';
							} else {
								return '<a href="'.$link.'" target="_blank" title="'.msg('preview').'"><img src="'.$file_pic.'" /></a>';
							}
						} else {
							return $link.'---';
						}
					}
					return '---';
				}
			}
			$inf['default'] = cleanForm($inf['default']);//cleanup data
			//new
			if (!is_array($inf['param2'])) {
				$link = $inf['path'] . $inf['default'][$key];

				if ($inf['default'][$key]) {
					$remove = ' <input type="hidden" name="'.$key.'_default" value="'.$link.'" /><img src="im/remove.png" link="'.$link.'" class="remove_'.$key.' fw-point" alt="'.INF_REMOVE.'" title="'.INF_REMOVE.'"/>';
				}
				$r = ' <input type="file"'.$style.$inf['addon_field'].' name="'.$key.'" />'.$remove;
				return $r.'<script type="text/javascript">
					$(".remove_'.$key.'").click(function(){
						var $tr = $(this).parents("tr");
						$tr.children(".fw-form_head").children("a").remove();
						$tr.children(".fw-form_head_r").children("a").remove();
						$tr.find("input[name='.$key.'_default]").remove();
						$(this).remove();
					});
				</script>';
			} else {
				if (is_file($link)) {
					$remove = ' <input type="hidden" name="'.$key.'_default" value="'.$inf['default']['file'].'" /><img src="im/remove.png" link="'.$link.'" class="remove fw-point" alt="'.INF_REMOVE.'" title="'.INF_REMOVE.'"/>';
				}
				if ($inf['readonly'] == 1) {
					$readonly = ' readonly';
				}
				if (!isset($inf['param2']['descr'])) {
					$inf['param2']['descr'] = 0;
				}
				if (!isset($inf['param2']['mini'])) {
					$inf['param2']['mini'] = 0;
				}
				$style = '';
				if ($inf['param1']) {
					$style = ' size="'.$inf['param1'].'"';
					$txtstyle = ' style="width: '.($inf['param1']*8).'px;"';
				}
				if ($inf['param2']['mini'] == 1 || $inf['param2']['descr'] == 1) {
					$r = INF_FILE_BIG;
				}
				$r = ' <input type="file"'.$style.$inf['addon_field'].' name="'.$key.'_b" />';
				//set hidden file name for
				if ($inf['param2']['name'] == 'F') {
					$r .= '<input type="hidden" name="old_file_name" value="'.$link.'"/>';
				}
				if ($inf['param2']['mini'] == 1) {
					$r .= '<br/>'.INF_FILE_SMALL.' <input type="file"'.$style.$inf['addon_field'].' name="'.$key.'_s" />';
				}
				if ($inf['param2']['descr'] == 1) {
					$r .= '<br/>'.INF_FILE_DESCR.' <input type="text"'.$txtstyle.' name="'.$key.'_descr" value="'.$inf['default']['descr'].'" maxlength="200"/>';
				}
				if ($inf['append']) {
					$r .= ' '.$inf['append'];
				}
				if (is_file($link)) {
					$r .= ' '.$remove;
				}
				$r .= '
				<script type="text/javascript">
				$(document).ready(function(){
					$(".remove").click(function(){
						var $tr = $(this).parents("tr");
						$tr.children(".fw-form_head").children("a").remove();
						$tr.find("input[name=\''.$key.'_default\']").remove();
						$(this).remove();
					});
				});
				</script>';
				return $r;
			}
		}
	}
}

/**
 * return icon download and preview
 * Enter description here ...
 *
 * $key = 'file';
 * $basics = array('entity' => 'quotations', );
 * $inf = array('default' => array('file_updated' => '2010-01-18', 'file_updated_by' => 1, 'file' => 'file_name'));
 * form_file_preview($key, $basics, $inf)
 * @param unknown_type $key
 * @param unknown_type $basics
 * @param unknown_type $inf
 */
function form_file_preview($key, $basics, $inf){
	
	$file_updated = $inf['default'][$key.'_updated'];
	$updated_by = $inf['default'][$key.'_updated_by'];
	$file_name = $inf['default'][$key];

	$entity = $basics['entity'];
	$id = $basics['id'];

	if ($file_updated) {
		$ext = fw_file_extension($file_name);
		$name = fw_file_name($file_name);
		$add_link = '&entity=' . $entity . '&date=' . $file_updated . '&id=' . $id . '&key=' . $key . '&file_name=' . $name . '&type=' . $ext . '&fajax=1';

		//download
		$link = 'index.php?mod=file&view=download3&path=1' . $add_link;
		$file_pic = FRAMEWORK_IMG.'file_download.png';
		$file = ' <a target="_blank" href="'.$link.'"><img title="Download File" src="'.$file_pic.'" /></a>';


		$type_preview = array('png', 'bmp', 'gif', 'jpg', 'jpeg', 'pdf', 'pdf');
		//echo $ext;
		//check file extension that allow to preview
		if (in_array($ext, $type_preview)) {
			if ($ext == 'pdf') {
				$file .= ' <a onclick="show_popup_link(this, \'mod=file&view=preview3' . $add_link . '&type=' . $ext . '&path=1\',0,\'auto\',1);" href="#preview"><img src="im/file_preview.png" title="'.$entity.' '.$id.'"/>'.$show_act.'</a>';
				//$file .= ' <a href="tools/pdf/viewer.php?'.$add_link.'" target="_blank"><img src="im/file_preview.png" title="'.$param['info'].'"/>'.$show_act.'</a>';
			} else {
				//TODO check again
				$file_info = fw_file_details($entity, $file_updated, $id, $key, $name, $ext);
				$dir_tmp = 'files/temp/';
				$original = $inf['path'].$file_info['file_path'];
				$file_name_download = $file_info['file_name_download'];

				$file .= '<a class="fancybox" title="'.$entity.' '.$id.'" href="index.php?mod=file&view=preview3&path=1&type=' . $ext . $add_link . '">
					<img alt="'.$file_name_download.'" src="im/file_preview.png"/>
					</a>';
			}
		}
	}
	return $file;
}

/**
 * show text
 *
 * @param $key
 * @param $inf
 * @return unknown
 */
function form_text_plain($key, $inf, $act = 'form', $post = ''){
	if (function_exists($inf['call_function'])) {
		$inf['default'] = $inf['call_function']($key, $inf);
	}
	if ($inf['displayonly'] == 1) {
		if ($inf['default'] != '') {
			if (isset($inf['call_function'])) {
				$inf['default'] = '<span name="'.$key.'">'.$inf['default'].'</span>';
			}
			return $inf['default'].$inf['append'];//clean($inf['default']).$inf['append'];
		} else {
			return;
		}
	}
	return '<span id="text_'.$key.'" '.$inf['addon_field'].'>'.clean($inf['default']).'</span>'.$inf['append'];
}

/**
 * EXAMPLE : $fields['annual_fee'] = array(
 * 'head' => 'Annual fee','type' => 'money','param1' => array('M' => '100','C' => '50'),
 * 'values' => array('currency' => array('test1','test2')),'param2' => '20','Z' => 1
 * );
 * currency' == 0 dont have field currency , currency == 1
 */
function form_money($key, $inf, $act = 'form', $post = '') {
	//display detail
	switch($act) {
		case 'search_result':{
			return array(
				'format_money' => array(
					'MK' => 'Example: 1K',
					'MKC' => 'Example: 1K THB',
					'M' => 'Example: 1,000',
					'MC' => 'Example: 1,000 THB',
				),
			);
		} break;
		case 'validate':{
			$a = 0;
			if ($inf['readonly'] != 1) {
				if (empty($post[$key])) {
					++$a;
				}
				if (!isset($inf['currency']) && empty($post[$key.'_currency'])) {
					++$a;
				}
				if ($a > 0) {
					return $key;
				}
			}
			return false;
		} break;
		case 'update':{
			//SET default values
			$po[$key] = $post[$key];
			$po[$key.'_currency'] = $post[$key.'_currency'];
			//;
			if ($post[$key.'_currency']) {
				$post[$key.'_currency'] = '"'.$post[$key.'_currency'].'"';
			} else {
				$post[$key.'_currency'] = 'NULL';
			}
			if ($post[$key]) {
				$post[$key] = '"'.$post[$key].'"';
			} else{
				$post[$key] = 'NULL';
				$post[$key.'_currency'] = 'NULL';
			}
			if ($basics['log_removed'] == 2 && ($post['opt'] == 4 || $_POST['opt4'])) {
				$qry .= '`'.$key.'`=NULL';
				if ($vl['currency'] != 0 || !isset($vl['currency'])) {
					$qry .= ', `'.$key.'_currency`=NULL';
				}
			} else {
				$qry .= '`'.$key.'`='.$post[$key];
				if (isset($_POST[$key.'_currency'])) {
					$qry .= ', `'.$key.'_currency`='.$post[$key.'_currency'];
				}
			}
			return array('qry' => $qry, 'po' => $po);
		} break;
		default: {
			$r = '';
			if ($inf['displayonly'] == 1) {
				if (isset($inf['default']['money'])) {
					if ($inf['sortable'] == 1) {
						$r .= '<span class="hide">'.$inf['default']['money'].'</span>';
					}

					if ($inf['decimal'] == 1) {
						$r .= format_money($inf['default']['money']).' ';
					} else {
						$r .= format_money($inf['default']['money'], 2).' ';
					}

					if ($inf['currency'] != '0' || !isset($inf['currency'])) {
						$r .= $inf['default']['currency'];
					}

					if ($inf['append']) {
						$r .= $inf['append'];
					}

					$r = $inf['prepend'] . '<div style="float: right;" class="m_'.$key.'">'.$r.'</div>';
				} else {
					$r = '';
				}
				return $r;
			}
			//set money format
			if (is_array($inf['param1'])) {
				if ($inf['param1']['M'] || $inf['param1']['money']) {
					$money_param1 = $inf['param1']['M'];
				} else {
					$money_param1 = '60';
				}

				if ($inf['param2']['M'] || $inf['param1']['money']) {
					$money_param2 = $inf['param2']['M'];
				} else {
					$money_param2 = '60';
				}

				if ($inf['param1']['C'] || $inf['param1']['currency']) {
					$currency_param1 = $inf['param1']['C'];
				} else {
					$currency_param1 = '30';
				}

				if ($inf['param2']['C'] || $inf['param1']['currency']) {
					$currency_param2 = $inf['param2']['C'];
				} else {
					$currency_param2 = '30';
				}
			} else {
				$money_param1 = '100';
				$money_param2 = '60';

				$currency_param1 = '30';
				$currency_param2 = '30';
			}

			$money_default = $inf['default']['money'];
			if ($inf['default']['currency']) {
				$currency_default = $inf['default']['currency'];
			}

			//set money/currency format
			$pattern = "!(\[(.*)\])!Uis";
			preg_match($pattern, $key, $matches);
			if ($matches) {
				$currency_name = str_replace($matches[0], '', $key).'_currency'.$matches[0];
				$show_name = str_replace($matches[0], '', $key).'_show'.$matches[0];
				$key_class = str_replace('[', '_', str_replace(']', '_', $key)).'class';
			} else {
				$currency_name = $key.'_currency';
				$show_name = $key.'_show';
				$key_class = $key;
			}

			if ($inf['prepend']) {
				$r .= $inf['prepend'];
			}

			$addon_field = '';
			if ($inf['addon_field'] && !is_array($inf['addon_field'])) {
				//$inf['addon_field'] = array('money' => $inf['addon_field'], 'currency' => $inf['addon_field']);
				$addon_field = $inf['addon_field'];
			}

			$r .= form_input($show_name, array('param1' => $money_param1.'|R', 'param2' => $money_param2, 'default' => format_money($money_default,2), 'req' => $inf['req'], 'addon_field' => $addon_field . ' onkeypress="return filterInput(1, event, true, \'-\');" onchange="copy_number(this,\''.$key_class.'\');' . $inf['addon_field']['money'] . '"', 'readonly' => $inf['readonly']));
			$r .= '<input type="hidden" name="'.$key.'" value="'.$money_default.'" class="'.$key_class.'"/>';

			//dont show currency fields
			if (!isset($inf['currency'])) {
				if (count($inf['values']['currency']) == 1 || count($inf['values']['C']) == 1) {
					if ($inf['values']['currency'][0]) {
						$c = array_values($inf['values']['currency']);
					} else {
						$c = array_values($inf['values']['C']);
					}
					//$r .= ' ' . $c[0] . '<input type="hidden" name="'.$key.'_currency" value="'.$c[0].'"/>';
					$r .= ' ' . $c[0];
					if (!$inf['no_hidden_currency']) {
						$r .= '<input type="hidden" name="'.$key.'_currency" value="'.$c[0].'"/>';
					}
				} else if (is_array($inf['values']['currency']) || is_array($inf['values']['C'])) {
					$r .= ' ' . form_select($currency_name, array('values' => ($inf['values']['currency'])?$inf['values']['currency']:$inf['values']['C'],'param2' => 'N','default' => $currency_default,'req' => $inf['req'],'addon_field' => $addon_field . $inf['addon_field']['currency']));
				} else {
					$r .= ' ' . form_input($key.'_currency', array('param1' => $currency_param1, 'param2' => $currency_param2, 'default' => $currency_default, 'req' => $inf['req'], 'addon_field' => $addon_field . $inf['addon_field']['currency']));
				}
			}

			if ($inf['append']) {
				$r .= $inf['append'];
			}
			return $r;
		}
	}
}

function form_phone($key,$inf,$act='form',$post=''){
	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'update':{
			//SET default values
			$po[$key] = $post[$key];
			$po[$key.'_ext'] = $post[$key.'_ext'];
			if ($basics['log_removed'] == 2 && ($post['opt'] == 4 || $_POST['opt4'])) {
				$qry .= '`'.$key.'`=NULL,`'.$key.'_ext`=NULL';
			} else {
				$qry .= '`'.$key.'`="'.$post[$key].'",`'.$key.'_ext`="'.$post[$key.'_ext'].'"';
			}
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			if ($inf['displayonly'] == 1) {
				$r = $inf['default']['phone'].' ';
				if ($inf['default']['ext']) {
					if ($inf['values']['ext']) {
						$r .= INF_EXT.'.: '.$inf['values']['ext'][$inf['default']['ext']];
					} else {
						$r .= '<span class="fw-form_head">'.INF_EXT.'.:</span> '.$inf['default']['ext'];
					}
				}
				return $r;
			}

			//set money format
			if (is_array($inf['param1'])) {
				$phone_param1 = '60';
				$ext_param1 = '30';
				if ($inf['param1']['T']) {
					$phone_param1 = $inf['param1']['T'];
				}
				if ($inf['param1']['E']) {
					$ext_param1 = $inf['param1']['E'];
				}
			} else {
				$phone_param1 = '60';
				$ext_param1 = '30';
			}

			if (is_array($inf['param2'])) {
				$phone_param2 = '60';
				$ext_param2 = '30';
				if ($inf['param2']['T']) {
					$phone_param2 = $inf['param2']['T'];
				}
				if ($inf['param2']['E']) {
					$ext_param2 = $inf['param2']['E'];
				}
			} else {
				$phone_param2 = '60';
				$ext_param2 = '30';
			}
			//check default values
			if ($inf['default']['phone']) {
				$phone_default = $inf['default']['phone'];
			}
			if ($inf['default']['ext']) {
				$ext_default = $inf['default']['ext'];
			}

			//set money/currency format
			$r .= form_input($key, array('param1' => $phone_param1, 'param2' => $phone_param2, 'default' => $phone_default, 'req' => $inf['req'], 'addon_field' => $inf['addon_field']));
			$r .= ' <span class="fw-form_head">'.INF_EXT.':</span> '.form_input($key.'_ext', array('param1' => $ext_param1, 'param2' => $ext_param2, 'default' => $ext_default, 'req' => $inf['req']));
			return $r;
		}
	}
}

/**
 *
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * $fields['client_name'] = array('head' => msg('client_name'),'type' => 'content','default' => '<span name="client_name"></span>','skip' => 1,'zone' => 1);
 * @return <span name="client_name"></span>
 */
function form_content($key, $inf, $act = 'form', $post = ''){
	return $inf['default'];
}

/**
 * TODO not finish
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * EXAMPLE: $fields['slide'] = array('head' => 'slide','type' => 'slide','values' => array('min' => 0,'max' => 100,'step' => 10),'zone' => 1);
 * @return unknown_type
 */
function form_slide($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
//			if (!isset($post[$key]) || $post[$key] == '') return $key;
			return;
		} break;
		case 'update':{
			//SET default values
			if ($post[$key] != '') {
				$qry .= SQL('`'.$key.'`=%d',$post[$key]);
			}
			return array('qry' => $qry);
		} break;
		default:{
			if (!$inf['values']['min']) {
				$inf['values']['min'] = 0;
			}
			if (!$inf['values']['max']) {
				$inf['values']['max'] = 100;
			}
			if (!$inf['values']['step']) {
				$inf['values']['step'] = 10;
			}
			$a = floor(255 / ($inf['values']['max'] / $inf['values']['step']));
			$width = '190';
			if ($inf['param1']) {
				$width = $inf['param1'];
			}
			//set color
			if (!$inf['default']) {
				$inf['default'] = $inf['values']['min'];
			}
			$c = floor(($inf['default'] / $inf['values']['step']) * $a) - 50;

			if ($inf['displayonly'] == 1) {
				return '<span class="slide_'.$key.' fw-field-slide-status" style="background-color: rgb(0, '.$c.', 0);">'.$inf['default'].'%</span>';
			}
			$r = '<div id="'.$key.'_slider" style="margin-left: 40px; width: '.$width.'px;">
			<span class="slide_'.$key.' fw-field-slide-status" style="position: relative; left: -40px; top: -3px; background-color: rgb(0, '.$c.', 0);">'.$inf['default'].'%</span>
			</div>
			<input type="hidden" name="'.$key.'" value="'.$inf['default'].'"/>';
			$r .= '<script type="text/javascript">
					var '.$key.'_slider_old = '.(int)$inf['default'].';
					$(document).ready(function(){
						$("#'.$key.'_slider").slider({
							value: "'.$inf['default'].'",
							min: '.$inf['values']['min'].',
							max: '.$inf['values']['max'].',
							step: '.$inf['values']['step'].',
							change: function(event, ui){
								rgb = ((ui.value / '.$inf['values']['step'].')*'.$a.') - 50;
								$("#'.$key.'_slider span").css("background-color","rgb(0,"+rgb+",0)").css("color","#FFF");
								$("#'.$key.'_slider span").html(ui.value+"%");
								$("input[name='.$key.']").val(ui.value);
							},
							slide: function(event, ui) {
								'.$key.'_slider_old = ui.value;
							}
						});
					});
			</script>';

			return $r;
		}
	}

}

/**
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * EXAMPLE: $fields['country'] = array('param1' => '250|F'); //for show flag and no need to set 'values'
 * Other EXAMPLE: same with form_select
 * @return unknown_type
 */
function form_country($key, $inf, $act = 'form', $post = ''){
	global $countries;
	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'update':{
			if ($inf['vhead'] && $post[$key] == $inf['vhead']) {
				$post[$key] = 'NULL';
			}
			$po[$key] = $post[$key];
			$qry = '`'.$key.'`='.intoDB($post[$key],'S');
			return array('qry' => $qry, 'po' => $po);
		} break;
		default:{
			$inf['values'] = $countries;
			//detail
			if ($inf['displayonly'] == 1) {
				if ($inf['default']) {
					if (strstr($inf['param1'], 'F')) {
						$r .= '<img src="im/flag/'.$inf['default'].'.gif"> ';
					}
					$r .= $countries[$inf['default']];
					if ($inf['append']) {
						$r .= $inf['append'];
					}
				}
				return $r;
			}
			//edit
			if (strstr($inf['param1'], 'F')) {#flag
				if ($inf['default']) {
					$flag = '<img src="im/flag/' . $inf['default'] . '.gif"> ';
				}
				$inf['param1'] = str_replace(array('F', '|'), array('', ''), $inf['param1']);
				$inf['append'] .= ' <span>'.$flag.'</span>';
				$js_script = '
				<script type="text/javascript">
					$(document).ready(function(){
						$("select[name='.$key.']").change(function(){
							country_code = $(this).val();
							if (country_code != "" && country_code != undefined) {
								$(this).next("span").html(\'<img src="im/flag/\'+country_code+\'.gif">\');
								$(this).next("span").show();
							} else {
								$(this).next("span").hide();
							}
						});
					});
				</script>';
			}
			$r = form_select($key, $inf);

			return $r.$js_script;
		}
	}
}

/**
 *
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * @return unknown_type
 */
function form_name($key, $inf, $act = 'form', $post = ''){
	global $global_config;

	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'update':{
			if ($post['merge'] == 1) {
				$qry = SQL('`'.$key.'`=%s, `'.$key.'_title`=%s, `'.$key.'_first`=%s, `'.$key.'_middle`=%s, `'.$key.'_last`=%s, `'.$key.'_suffix`=%s, `'.$key.'_initials`=%s, `'.$key.'_display`=%s, `'.$key.'_keep`=%s ', $post[$key], $post[$key.'_title'], $post[$key.'_first'], $post[$key.'_middle'], $post[$key.'_last'], $post[$key.'_suffix'], $post[$key.'_initials'], $post[$key.'_display'], $post[$key.'_keep']);
				return array('qry' => $qry);
			} else {
				$qry = SQL('`'.$key.'`=%s, `'.$key.'_title`=%s, `'.$key.'_first`=%s, `'.$key.'_middle`=%s, `'.$key.'_last`=%s, `'.$key.'_suffix`=%s, `'.$key.'_initials`=%s, `'.$key.'_display`=%s, `'.$key.'_keep`=%s ', $post[$key], $post['fw_'.$key.'_title'], $post['fw_'.$key.'_first'], $post['fw_'.$key.'_middle'], $post['fw_'.$key.'_last'], $post['fw_'.$key.'_suffix'], $post['fw_'.$key.'_initials'], $post['fw_'.$key.'_display'], $post['fw_'.$key.'_keep']);
				
				return array('qry' => $qry, 'po' => $po);
			}
		} break;
		default:{
			if ($inf['search'] == 1) {
				return form_input($key, $inf);
			}

			//detail
			if ($inf['displayonly'] == 1) {
				if ($_REQUEST['view'] == 'merge') {
					$r = clean($inf['default'][$key.'_display']);
				} else {
					if ($inf['default'][$key]) {
						$r = clean($inf['default'][$key.'_display']);
						if ($inf['append']) {
							$r .= $inf['append'];
						}
					}
				}
				return $r;
			}

			$sk .= '<script type="text/javascript">';
			//define title
			$title_arr_show = array(
				'mr' => array('Mr', 'Mr.'),
				'mrs' => array('Mrs', 'Mrs.'),
				'ms' => array('Ms', 'Ms.'),
				'miss' => array('Miss', 'Miss'), 
				'dr' => array('Dr', 'Dr.'),
				'prof' => array('Prof', 'Prof'),
				'khun' => array('Khun', 'K.'),
				'ml' => array('ML', 'M.L.'),
			);
			foreach ($title_arr_show as $k => $v) {
				$sk .= 'name_prefix["'.strtolower($v[0]).'"] = "'.$v[0].'";
				';
				$title_arr[] = $v[(int)($global_config['system']['name_trim_dots']+1)%2];
				$a_name = $v[0];
				unset($v[0]);
				if ($v) {
					foreach ($v as $k2 => $v2) {
						$key_u = strtolower($v2);
						$sk .= 'name_prefix["'.$key_u.'"] = "'.$a_name.'";
						';

						if ($global_config['system']['name_trim_dots'] == 1) {
							$sk .= 'name_prefix["'.$key_u.'"] = "'.$a_name.'";
							';
						} else {
							$sk .= 'name_prefix["'.$key_u.'"] = "'.$v2.'";
							';
						}
					}
				}
			}	
			//define suffix
			//$suffix_arr = array('Jr', 'Sr', 'MD', 'PHD', 'MA', 'I', 'II', 'III');
			$suffix_arr_show = array(
				'jr' => array('Jr', 'Jr.'), 
				'sr' => array('Sr', 'Sr.'), 
				'md' => array('MD', 'M.D.', 'MD.'), 
				'phd' => array('PHD', 'PH.D.', 'PH.D'),
				'ma' => array('MA', 'M.A.', 'MA.'),
				'i' => array('I', 'I.'),
				'ii' => array('II', 'II.'),
				'iii' => array('III', 'III.')
			);
			
			foreach ($suffix_arr_show as $k => $v) {
				$sk .= 'name_suffix["'.strtolower($v[0]).'"] = "'.$v[0].'";
				';
				$suffix_arr[] = $v[(int)($global_config['system']['name_trim_dots']+1)%2];
				$a_name = $v[0];
				unset($v[0]);
				if ($v) {
					foreach ($v as $k2 => $v2) {
						$key_u = strtolower($v2);
						$sk .= 'name_suffix["'.$key_u.'"] = "'.$a_name.'";
						';

						if ($global_config['system']['name_trim_dots'] == 1) {
							$sk .= 'name_suffix["'.$key_u.'"] = "'.$a_name.'";
							';
						} else {
							$sk .= 'name_suffix["'.$key_u.'"] = "'.$v2.'";
							';
						}
					}
				}
			}
			$sk .= '</script>';

			if ($inf['duplicate_check'] == 1) {
				unset($inf['duplicate_check']);
				$rel = 'fw_'.$key.'_full';
				$js_script = '<div id="notify_duplicated_'.$rel.'"></div>
				<script type="text/javascript">
					$(document).ready(function(){
						$( "#'.$rel.'" ).change(function(){
							$.post("index.php?fajax=1&mod=entities&view=duplicate_checked",
							{
								entity: "'.$inf['entity'].'",
								entity_name: $(this).val(),
								entity_name_first: $("input[name=fw_'.$key.'_first]").val(),
								entity_name_last: $("input[name=fw_'.$key.'_last]").val(),
								entity_id: $("input[name=id]").val(),
								entity_field: "'.$key.'",
							},
								function(data){
									$("#notify_duplicated_'.$rel.'").html(data);
							});
						});
					});
				</script>';
			}
			
			$inf['addon_field'] = ' onchange="fw_fields_name_check_word(this, \''.$key.'\', \'n\', \''.$global_config['system']['name_trim_dots'].'\', \''.$global_config['system']['name_last_name'].'\');" id="fw_'.$key.'_full"';//onkeyup
			$infx = $inf;
			unset($infx['default']);
			$infx['default'] = $inf['default'][$key];
			
			$first_name = '<input type="hidden" name="fw_'.$key.'_first" value="'.clean($inf['default'][$key.'_first']).'"/>';
			$last_name = '<input type="hidden" name="fw_'.$key.'_last" value="'.clean($inf['default'][$key.'_last']).'"/>';
			if ($global_config['system']['name_last_name'] == 'last') {
				$a = $last_name;
				$b = $first_name;
			} else {
				$b = $last_name;
				$a = $first_name;
			}
			$r = form_input($key, $infx);
			$r .= ' <input type="button" class="btn small blue awesome" name="customize" value="'.msg('customize').'" style="padding: 3px;" onclick="fw_field_name_load_form(\'<form>\'+$(\'#'.$key.'_name_field\').html()+\'</form>\', \''.$key.'\');"/>
			<div id="fw_'.$key.'_fields_hidden">
				<input type="hidden" name="fw_'.$key.'_title" value="'.clean($inf['default'][$key.'_title']).'"/>
				'.$a.'
				<input type="hidden" name="fw_'.$key.'_middle" value="'.clean($inf['default'][$key.'_middle']).'"/>
				'.$b.'
				<input type="hidden" name="fw_'.$key.'_suffix" value="'.clean($inf['default'][$key.'_suffix']).'"/>
				<input type="hidden" name="fw_'.$key.'_initials" value="'.clean($inf['default'][$key.'_initials']).'"/>
				<input type="hidden" name="fw_'.$key.'_display" value="'.clean($inf['default'][$key.'_display']).'"/>
				<input type="hidden" name="fw_'.$key.'_keep" value="'.clean($inf['default'][$key.'_keep']).'"/>
			</div>
			';
			
			if ($global_config['system']['name_last_name'] == 'first') {
				$name_a = '<td>'.msg('fw_name_first').':</td><td>'.form_input($key.'_first', array('param1' => 120, 'addon_field' => ' class="fw_'.$key.'_fields"')).'<input type="hidden" name="'.$key.'_middle" class="fw_'.$key.'_fields"/></td>';
				$name_b = '<td>'.msg('fw_name_last').':</td><td colspan="3">'.form_input($key.'_last', array('param1' => 244, 'addon_field' => ' class="fw_'.$key.'_fields"')).'</td>';
			} else {
				$name_a = '<td>'.msg('fw_name_last').':</td><td>'.form_input($key.'_last', array('param1' => 120, 'addon_field' => ' class="fw_'.$key.'_fields"')).'</td>';
				$name_b = '<td>'.msg('fw_name_first').':</td><td colspan="3">'.form_input($key.'_first', array('param1' => 244, 'addon_field' => ' class="fw_'.$key.'_fields"')).'<input type="hidden" name="'.$key.'_middle" class="fw_'.$key.'_fields"/></td>';
			}
			$r .= '
				<div id="'.$key.'_name_field" class="hide">
					<div class="popupHeader">'.msg('fw_edit_contact_name').'</div>
					<div class="detailsInfo">
					<form action="">
						<table cellpadding="4" cellspacing="1">
							<tr><td>'.msg('fw_name_title').':</td><td colspan="3">'.form_select($key.'_title', array('values' => $title_arr, 'param1' => 100, 'param2' => 'N', 'addon_field' => ' class="fw_'.$key.'_fields"')).'</td></tr>
							<tr>
								'.$name_a.'	
								<td>'.msg('fw_name_initial').':</td><td>'.form_input($key.'_initials', array('param1' => 55, 'param2' => 1, 'addon_field' => ' class="fw_'.$key.'_fields"')).'</td>
							</tr>
							<tr>
								'.$name_b.'
							</tr>
							<tr>
								<td>'.msg('fw_name_suffix').':</td><td colspan="3">'.form_select($key.'_suffix', array('values' => $suffix_arr, 'param1' => 100, 'param2' => 'N', 'addon_field' => ' class="fw_'.$key.'_fields"')).'</td>
							</tr>
							<tr>
								<td colspan="4">'.form_checkbox($key.'_custom', array('values' => array(1 => msg('keep custom name')), 'single' => 1)).'</td>
							</tr>
							<tr>
								<td colspan="4" align="right"><input type="button" name="submit_a" value="'.msg('submit_name').'" class="btn medium green awesome btn-add" onclick="fw_fields_name_update_word(this,\''.$key.'\');"/></td>
							</tr>
						</table>
					</form>
					</div>
				</div>';
			return $r.$sk.$js_script;
		}
	}
}

function form_items_complete($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'update':{
//			if ($_POST[$key . '_item_id']) {
//				foreach ($_POST[$key . '_item_id'] as $type) {
//
//				}
//				//$qry = SQL('`'.$key.'`=%s', implode(',', $_POST[$key . '_item_id']));
//			} else {
//				$qry = SQL('`'.$key.'`=NULL');
//			}
//			return array('qry' => $qry);
//			echo $qry;
		} break;
		default:{
			if ($inf['search'] == 1) {
//				return form_input($key, $inf);
			}

			//detail
			if ($inf['displayonly'] == 1) {
				if ($inf['default']) {
					foreach ($inf['default'] as $items => $group) {
						if ($group) {
							foreach ($group as $items_id => $v) {
								$r .= $inf['param2']['list'][$items][$items_id].'<br/>';
							}
						}
					}
					return $r;
				}
//				if ($_REQUEST['view'] == 'merge') {
//					if ($inf['default'][$key.'_first']) {
//						$r = clean($inf['default'][$key.'_first']);
//					}
//					if ($inf['default'][$key.'_last']) {
//						$r .= ' ' . clean($inf['default'][$key.'_last']);
//					}
//				} else {
//					if ($inf['default'][$key]) {
//						$r = clean($inf['default'][$key]);
//						if ($inf['append']) {
//							$r .= $inf['append'];
//						}
//					}
//				}
//				return $r;
			}
			$key = str_replace('[', '_', $key);
			$key = str_replace(']', '_', $key);
			if ($inf['default']) {
				foreach ($inf['default'] as $items => $group) {
					if ($group) {
						foreach ($group as $items_id => $v) {
							$default_display .= '<div id="item_id_'.$key.'_'.$items.'_'.$items_id.'" style="padding-top: 5px;"> ' . $inf['param2']['list'][$items][$items_id] . ' <a href="#remove" onclick="$(\'#item_id_'.$key.'_'.$items.'_'.$items_id.'\').remove();"><img src="im/remove.png"/></a><input type="hidden" value="'.$items_id.'" name="'.$key.'_item_id['.$items.'][]"/></div>';
						}
					}
				}
			}

			$r = form_input($key, array('param1' => $inf['param1'], 'addon_field' => ' id="' . $key . '_box" onkeypress="return note_mail_key_press(event, this);" mail_type="'. $v .'"')).'
			<div id="' . $key. '_details">'.$default_display.'</div>';
			$r .= '
			<script type="text/javascript">
				$("#' . $key . '_box").autocomplete2("index.php?fajax=1&mod=fw&view='.$inf['param2']['view'].'&item_id='.$inf['param2']['item_id'].'&item='.$inf['param2']['item'].'", {
					minChars: 0,
					width: 330,
					matchContains: "word",
					autoFill: false,
					formatItem: box_autocomplete_item,
					formatMatch: box_autocomplete_format,
					formatResult: box_autocomplete_result
				});

				$("#' . $key . '_box").result(function(event, json, formatted) {
					data = eval("("+json+")");
				';
					if ($inf['param2']['single'] == 1) {
						$r .= '$("div[id^=item_id_'.$key.'_]").remove();';
					} else {
						$r .= '$("#item_id_'.$key.'_"+data.type+"_"+data.id).remove();';
					}
				$r .= '
					$("#' . $key . '_details").append("<div id=\'item_id_'.$key.'_"+data.type+"_"+data.id+"\' style=\'padding-top: 5px;\'>" + data.name + " <a href=\\"#remove\\" onclick=\'$(\\"#item_id_'.$key.'_" + data.type + "_" + data.id + "\\").remove();\'><img src=\'im/remove.png\'/><input type=\\"hidden\\" name=\\"'.$key.'_item_id["+data.type+"][]\\" value=\'"+data.id+"\'/></a></div>");
					$(event.target).val("");
				});
			</script>
			';
			return $r;
		}
	}
}

/**
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * EXAMPLE: form_color('minicolor', array('default' => '#fc96ca', 'displayonly' => 1));
 * $fields['choose_color'] = array('head' => msg('color'), 'type' => 'color', 'zone' => 1);
 * @return color picker
 */
function form_color($key, $inf, $act = 'form', $post = ''){
	$js_readonly = '';
	switch($act) {
		case 'validate':{
			$inf['param1'] = strtolower($inf['param1']);
			return true;
		} break;
		case 'update':{
			$po[$key] = $post[$key];
			$qry = '`' . $key . '`=' . intoDB($post[$key]);
			return array('qry' => $qry, 'po' => $po);
		} break;
		default: {
			$inf['default'] = cleanForm($inf['default']);//cleanup data
			if ($inf['default'] == '') {
				$inf['default'] = '#000000';
			}
			if ($inf['readonly'] == 1) {
				$r = '<input type="hidden" name="'.$key.'" '.$inf['addon_field'].' readonly="readonly" class="minicolors" size="7" value="'.$inf['default'].'" />';
//				$js_readonly = '\'readonly\', false';
			// readonly;
			} else {
				if ($inf['displayonly'] == 1) {
					$r = '<input type="hidden" name="'.$key.'" value="'.$inf['default'].'" /><span class="fw-display-minicolors" style="background: '.$inf['default'].'; width: 20px; height: 20px; border: 1px solid black;"></span>';
				} else {
					$r = '<input type="hidden" name="'.$key.'" '.$inf['addon_field'].' class="minicolors" size="7" value="'.$inf['default'].'" />';
				}
				if ($inf['color_change']) {
					$js_readonly = '
						change: function(hex, rgb) {
							'.$inf['color_change'].'
						}';
				}

				//change name for fields
				//$pass_id is request variable we got it from cf
				if ($pass_id != '') {
					$pass_name = $key.'['.$pass_id.']['.$pass_id2.']';
				} else {
					$pass_name = $key;
				}
			}
			if ($inf['append']) {
				$r .= $inf['append'];
			}
			$js = str_replace(']', '\\\\]', str_replace('[', '\\\\[', $key));
			if ($inf['displayonly'] != 1) {
				$r .= '<script type="text/javascript">
						$("input[name='.$js.']").miniColors({
							'.$js_readonly.'
						});
					</script>';			
			}
			return $r;
		}
	}
}

/**
 * @param $key
 * @param $inf
 * @param $act
 * @param $post
 * EXAMPLE: form_user('minicolor', array('default' => '#fc96ca', 'displayonly' => 1));
 * $fields['manager'] = array('head' => msg('manager'), 'type' => 'user_name', 'zone' => 1);
 * @return color picker
 */
function form_user($key, $inf, $act = 'form', $post = ''){
	global $cache_user;

	$js_readonly = '';
	switch($act) {
		case 'search_result':{
			return array(
				'user_name' => array(
					'abbr' => msg('abbr'),
					'firstname' => msg('firstname'),
					'full' => msg('full'),
					'nickname' => msg('nickname'),
				),
			);
		} break;
		case 'validate':{
			if (!isset($post[$key]) || $post[$key] == '') {
				return $key;
			}
			return false;
		} break;
		case 'update':{
			$po[$key] = $post[$key];
			$qry = '`' . $key . '`=' . intoDB($post[$key]);
			return array('qry' => $qry, 'po' => $po);
		} break;
		default: {
			$users_arr = user_list(','.$inf['account_type'].',', $inf['visibility']);
			if ($inf['displayonly'] == 1) {
				$all = array();
				//flat second dimension and display value
				if ($users_arr['label']) {
					foreach ($users_arr['label'] as $k => $v) {
						if ($v) {
							foreach ($v as $k2 => $v2) {
								$all[$k2] = $v2;
							}
						}
					}
				}
				return clean($all[$inf['default']]) . $inf['append'];
			} else {
				if ($inf['search'] == 1) {
					if ($inf['param1']) {
						$width = $inf['param1'];
					}
					//beem comment
					$_REQUEST[$_REQUEST['entity']][$inf['f']] = $inf['default'];
					$selected[$_REQUEST[$_REQUEST['entity']][$inf['f']]] = ' selected="selected"';

					if ($inf['readonly'] == 1) {
						$readonly = ' readonly';
					}
					if ($inf['disabled'] == 1) {
						$readonly = ' disabled';
					}

					$r = '<select'.$readonly.' style="width: '.$width.'px;" name="'.$key.'">
						<option value=""></option>
						<option value="all"'.$selected['all'].'>all</option>
						<option value="none"'.$selected['none'].'>none</option>';
					foreach ($users_arr['label'] as $k => $v) {
						if ($v) {
							$each_id_dep = implode(',', array_keys($v));

							if ($selected[$each_id_dep] != "") {
								$search_text = $k;
							}
							$r .= '<option style="font-weight: bold;" value="'. $each_id_dep .'"'.$selected[$each_id_dep].'>'.$k.'</option>';
							asort($v);
							foreach ($v as $id => $name) {
								if ($selected[$id] != "") {
									$search_text = $name;
								}
								if ($id > 0) {
									$r .= '<option style="margin-left: 10px;" value="'.$id.'" '.$selected[$id].'>'.$name.'</option>';
								}
							}
						}
					}
					$r .= '</select>';
				} else {
					$inf['values'] = $users_arr;
					$r = form_select_group($key, $inf);
				}
			}
			return $r;
		}
	}
}

function user_list ($acc_type = '', $type = '') {
	global $cache_user, $cache_department;
	if ($acc_type == '') {
		$acc_type = ',all,';
	}
	sort_array_2d($cache_user, 'firstname');

	if ($type == 'managed') {
		$my_staff = $_SESSION[SESSION_A]['subordinate'];
		if (!is_array($my_staff)) {
			$my_staff = array();
		}
		array_push($my_staff, $_SESSION[SESSION_L]);
		foreach ($my_staff as $k => $v) {
			$department_name = $cache_department[$cache_user[$v]['id_department']]['department_name'];
			if ((strstr($acc_type, ','.$cache_user[$v]['account_type'].',') || ($acc_type == ',all,')) && $cache_user[$v]['user_status'] == 1) {
				$sales_arr['label'][$department_name][$v] = $cache_user[$v]['firstname'] . ' ' . $cache_user[$v]['lastname'] . ' ('.$cache_user[$v]['abbr'].')';
			}
		}
	} else if ($type == 'department') {
		foreach ($cache_user as $k => $v) {
			$department_name = $cache_department[$v['id_department']]['department_name'];
			if ((strstr($acc_type, ','.$v['account_type'].',') || ($acc_type == ',all,')) && $v['user_status'] == 1 && $v['id_department'] == $_SESSION[SESSION_A]['department']) {
				$sales_arr['label'][$department_name][$k] = $v['firstname'] . ' ' . $v['lastname'] . ' ('.$v['abbr'].')';
			}
		}
	} else if ($type == 'legal_entity') {
		foreach ($cache_user as $k => $v) {
			$department_name = $cache_department[$v['id_department']]['department_name'];
			if ((strstr($acc_type, ','.$v['account_type'].',') || ($acc_type == ',all,')) && $v['user_status'] == 1 && $v['id_le_en'] == $_SESSION[SESSION_A]['legal_entity']) {
				$sales_arr['label'][$department_name][$k] = $v['firstname'] . ' ' . $v['lastname'] . ' ('.$v['abbr'].')';
			}
		}
	} else if ($type == 'own') {
		$department_name = $cache_department[$_SESSION[SESSION_A]['department']]['department_name'];
		$sales_arr['label'][$department_name][$_SESSION[SESSION_L]] = $cache_user[$_SESSION[SESSION_L]]['firstname'] . ' ' . $cache_user[$_SESSION[SESSION_L]]['lastname'] . ' ('.$cache_user[$_SESSION[SESSION_L]]['abbr'].')';
	} else {
		foreach ($cache_user as $k => $v) {
			$department_name = $cache_department[$v['id_department']]['department_name'];
			if ((strstr($acc_type, ','.$v['account_type'].',') || ($acc_type == ',all,')) && $v['user_status'] == 1) {
				$sales_arr['label'][$department_name][$k] = $v['firstname'] . ' ' . $v['lastname'] . ' ('.$v['abbr'].')';
			}
		}
	}
	return $sales_arr;
}

function form_filter_by($key, $inf, $act = 'form', $post = ''){
	switch($act) {
		case 'validate':{
//			if (!isset($post[$key]) || $post[$key] == '') {
//				return $key;
//			}
//			return false;
		} break;
		case 'update':{
//			$po[$key] = $post[$key];
//			$qry = '`' . $key . '`=' . intoDB($post[$key]);
//			return array('qry' => $qry, 'po' => $po);
		} break;
		default: {
			if ($inf['displayonly'] == 1) {

			} else {
				if ($inf['search'] == 1) {
					$r = '<div class="entity_filter_by">';
					$char = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0');
					foreach ($char as $k => $v) {
						$bold = '';
						if ($_REQUEST[$inf['entity_key']][$inf['field'].'_filter_by'] == $v) {
							$bold = ' class="bold"';
						}

						if ($v == '0') {
							if ($bold != '') {
								$bold = ' class="bold span_last"';
							} else {
								$bold = ' class="span_last"';
							}
						}
						$r .= '<span'.$bold.'>'.$v.'</span>';
					}
					$r .= '<input type="hidden" name="'.$key.'" value="'.$_REQUEST[$inf['entity_key']][$inf['field'].'_filter_by'].'"/>';
					$script = '
						var tmp = $(this).html();
						if (tmp == "0") {
							tmp = "*";
						}
						$(this).parent().find("input").val(tmp);
					';

					$r .= '</div>
						<script type="text/javascript">
						$(document).ready(function(){
							$(".entity_filter_by").find("span").click(function(){
								'.$script.'
								$("#fw-search_form_'.$inf['entity_key'].'").ajaxSubmit({
									target: "#'.$inf['entity_key'].'_content",
								  	success: function(){//ui-state-default
								  		fw_effect_loading("", "", 1000);
									},
								});
							});
						});
					</script>';
					//<a onclick="load_page('#clients_content','index.php?ajax=1&amp;mod=clients&amp;entity=clients&amp;clients[sort_by]=gain_client.client_name&amp;clients[sort_order]=DESC&amp;clients[client_status]=&amp;clients[page]=0&amp;clients[limit]=20')" href="#ASC"><span style="padding-right: 20px; display: inline;" class="ui-icon ui-icon-triangle-1-n"></span> Name</a>
				} else {

				}
			}
			return $r;
		}
	}
}
?>